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

来源:互联网 发布:庇古的福利经济学知乎 编辑:程序博客网 时间:2024/05/19 02:05

一个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。可以参考: http://www.jianshu.com/p/dd79220b47dd)。

源码中layout_widthattr就能明白定义的默认值了。

<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_parentwrap_contentfill_parent(这种已经不推荐使用)。这三个值在attr中已经定义好了。可以直接使用;

b、如何使用自定义属性?

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

可以参考:

http://zhidao.baidu.com/link?url=-YS2G7N4ymwbEXA5wQE5mu9uvMiLc0UA9a7MBRiajCkpFQl3xX0oNzgHJB7lz9WZFlLoLiaY2UE5BC8zDkAMmDWUOojcyIjmbCELRM-XGoy

通过命名空间就可以使用自定义属性了。

<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”对应的value1

<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中定义的类型相似。

找到一篇不错的blog http://www.jianshu.com/p/2c566331a71d

2attr定义的enumflagvalue必须是数字。否则无法编译通过,类似于以下错误:

编译无法通过的Log

 

 

文章来源: 简书

0 0
原创粉丝点击