Android自定義控件必備知識——自定義屬性

ChaunceyJos 8年前發布 | 11K 次閱讀 安卓開發 Android開發 移動開發

一個Android開發者總會遇到自定義控件的問題,自定義控件開發也是由多個知識點組合起來的。這篇文章是自己學習自定義屬性時做的筆記和代碼。

a、如何自定義屬性

在res/values中的attrs.xml中自定義屬性。

<declare-styleable name="TestView">    
   <attr name="attrone" format="dimension"/>    
   <attr name="attrtwo" format="string" >    
    <enum name="one" value="0"/>    
    <enum name="two" value="1"/>
   </attr>
</declare-styleable>

分析一下以上代碼代表的含義:

declare-styleable: 表示一個屬性組。它的name必須和你自定義view的名字相同。

attr:表示單獨的一個屬性。format代表屬性的格式。格式包括很多種:比如顏色,數值,枚舉等。 看下圖:

formart屬性

attrtwo中定義了默認值enum(還可以定義flag。)

源碼中layout_width的attr就能明白定義的默認值了。

<declare-styleable name="ViewGroup_Layout">
   <attr name="layout_width" format="dimension">
     <enum name="fill_parent" value="-1" /> 
     <enum name="match_parent" value="-1" /> \
     <enum name="wrap_content" value="-2" /> 
  </attr> 
</declare-styleable>

通過以上的源碼和實際經驗我們知道。 給android:layout_width賦值時可以指定大小比如:10dp;也可以使用默認值:match_parent,wrap_content,fill_parent(這種已經不推薦使用)。這三個值在attr中已經定義好了。可以直接使用;

b、如何使用自定義屬性?

首先加入命名空間:xmlns:app=" http://schemas.android.com/apk/res-auto "

通過命名空間就可以使用自定義屬性了。

<com.mg.axe.androiddevelop.view.TestView   
   android:layout_width="match_parent"    
   android:layout_height="match_parent"    
   app:attrone="10dp"   
   app:attrtwo="two"    />

c、如何獲取自定義屬性 ?

通過getContext().obtainStyledAttributes()獲取TypedArray,

通過TypedArray來獲取自定義屬性的值。上代碼:

attrs中定義的自定義屬性:

<declare-styleable name="TestView">    
  <attr name="attrone" format="dimension"/>    
  <attr name="attrtwo" format="string" >    
    <enum name="one" value="0"/>    
    <enum name="two" value="1"/>
  </attr>
</declare-styleable>

布局文件中的使用:

將attrone設為10dp

將attrtwo設為默認值“two”對應的value為1

<LinearLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"   
  android:layout_width="match_parent"    
  android:layout_height="match_parent"    
  android:orientation="vertical">
  <com.mg.axe.androiddevelop.view.TestView   
     android:layout_width="match_parent"    
     android:layout_height="match_parent"    
     app:attrone="10dp"   
     app:attrtwo="two"    />
</LinearLayout>

獲取,并通過log打印出獲取的值:

public class TestView extends View{
   public TestView(Context context) {
     this(context,null);
   }

   public TestView(Context context, AttributeSet attrs) {
      this(context, attrs,0);
   }

   public TestView(Context context, AttributeSet attrs, int defStyleAttr) {
     super(context, attrs, defStyleAttr);
     TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.TestView);
     float attrone = ta.getDimension(R.styleable.TestView_attrone,0);
     Log.i("attrone's value",String.valueOf(attrone));
     String attrTwo = ta.getString(R.styleable.TestView_attrtwo);
     Log.i("attrTwo's value",attrTwo);

     / /測試代碼
     Log.i("attr's value",dp2px(10)+"");
 }
//測試代碼
 protected int dp2px(int dpval){
   return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dpval,getResources().getDisplayMetrics());
 }
}
10-08 18:07:39.536 6313-6313/com.mg.axe.androiddevelop I/attrone's value: 30.0
10-08 18:07:39.536 6313-6313/com.mg.axe.androiddevelop I/attrTwo's value: 1

10-08 18:07:39.536 6313-6313/com.mg.axe.androiddevelop I/attr's value: 30

運行程序之后可以看到獲取到了值。但是獲取到的值有些疑問: attrone設置的為10dp,為什么獲取到的值是30呢? 因為getDimension()方法中將dp轉化成了px。使用測試代碼證明了這個想法,源碼中也可以看出。

源碼中的 TypedValue.complexToDimension 方法就是轉化的代碼,自定義控件時經常需要將其他格式值轉為px不妨看看這里的源碼。

注意:并不是每個Android版本都將dp轉化成了px。這里需要調用以上測試代碼中的dp2px()方法做兼容。

public float getDimension(int index, float defValue) {
 if (mRecycled) {
   throw new RuntimeException("Cannot make calls to a recycled instance!");
 }
 index *= AssetManager.STYLE_NUM_ENTRIES;
 final int[] data = mData;
 final int type = data[index+AssetManager.STYLE_TYPE];
 if (type == TypedValue.TYPE_NULL) {
   return defValue;
 } else if (type == TypedValue.TYPE_DIMENSION) {
   return TypedValue.complexToDimension(data[index + AssetManager.STYLE_DATA], mMetrics);
 } else if (type == TypedValue.TYPE_ATTRIBUTE) {
   final TypedValue value = mValue;
   getValueAt(index*AssetManager.STYLE_NUM_ENTRIES, value);
   throw new UnsupportedOperationException( "Failed to resolve attribute at index " + index + ": " + value);
 }
 throw new UnsupportedOperationException("Can't convert to dimension: type=0x"
 + Integer.toHexString(type));
}

d、需要注意的問題

1、給某個自定義屬性賦值時,賦值的類型必須和format中定義的類型相似。

2、attr定義的enum和flag的value必須是數字。否則無法編譯通過,類似于以下錯誤:

編譯無法通過的Log

 

 

來自:http://www.jianshu.com/p/5ff5bb9a88f4

 

 本文由用戶 ChaunceyJos 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!