Android自定义控件必备知识——自定义属性

ChaunceyJos 7年前
   <p>一个Android开发者总会遇到自定义控件的问题,自定义控件开发也是由多个知识点组合起来的。这篇文章是自己学习自定义属性时做的笔记和代码。</p>    <p>a、如何自定义属性</p>    <p>在res/values中的attrs.xml中自定义属性。</p>    <pre>  <code class="language-java"><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></code></pre>    <p>分析一下以上代码代表的含义:</p>    <p>declare-styleable: 表示一个属性组。它的name必须和你自定义view的名字相同。</p>    <p>attr:表示单独的一个属性。format代表属性的格式。格式包括很多种:比如颜色,数值,枚举等。 看下图:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/26a2471eea8513eec629dcbadd61859b.png"></p>    <p style="text-align:center">formart属性</p>    <p>attrtwo中定义了默认值enum(还可以定义flag。)</p>    <p>源码中layout_width的attr就能明白定义的默认值了。</p>    <pre>  <code class="language-java"><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></code></pre>    <p>通过以上的源码和实际经验我们知道。 给android:layout_width赋值时可以指定大小比如:10dp;也可以使用默认值:match_parent,wrap_content,fill_parent(这种已经不推荐使用)。这三个值在attr中已经定义好了。可以直接使用;</p>    <p>b、如何使用自定义属性?</p>    <p>首先加入命名空间:xmlns:app=" http://schemas.android.com/apk/res-auto "</p>    <p>通过命名空间就可以使用自定义属性了。</p>    <pre>  <code class="language-java"><com.mg.axe.androiddevelop.view.TestView        android:layout_width="match_parent"         android:layout_height="match_parent"         app:attrone="10dp"        app:attrtwo="two"    /></code></pre>    <p>c、如何获取自定义属性 ?</p>    <p>通过getContext().obtainStyledAttributes()获取TypedArray,</p>    <p>通过TypedArray来获取自定义属性的值。上代码:</p>    <p>attrs中定义的自定义属性:</p>    <pre>  <code class="language-java"><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></code></pre>    <p>布局文件中的使用:</p>    <p>将attrone设为10dp</p>    <p>将attrtwo设为默认值“two”对应的value为1</p>    <pre>  <code class="language-java"><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></code></pre>    <p>获取,并通过log打印出获取的值:</p>    <pre>  <code class="language-java">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());   }  }</code></pre>    <pre>  <code class="language-java">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</code></pre>    <p>运行程序之后可以看到获取到了值。但是获取到的值有些疑问: <strong>attrone设置的为10dp,为什么获取到的值是30呢?</strong> 因为getDimension()方法中将dp转化成了px。使用测试代码证明了这个想法,源码中也可以看出。</p>    <p>源码中的 <strong>TypedValue.complexToDimension</strong> 方法就是转化的代码,自定义控件时经常需要将其他格式值转为px不妨看看这里的源码。</p>    <p>注意:并不是每个Android版本都将dp转化成了px。这里需要调用以上测试代码中的dp2px()方法做兼容。</p>    <pre>  <code class="language-java">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));  }</code></pre>    <p>d、需要注意的问题</p>    <p>1、给某个自定义属性赋值时,赋值的类型必须和format中定义的类型相似。</p>    <p>2、attr定义的enum和flag的value必须是数字。否则无法编译通过,类似于以下错误:</p>    <p><img src="https://simg.open-open.com/show/6313a5821457e84c3771d6e9e1ee5ac6.png"></p>    <p style="text-align:center">编译无法通过的Log</p>    <p> </p>    <p> </p>    <p>来自:http://www.jianshu.com/p/5ff5bb9a88f4</p>    <p> </p>