Android自定义属性的理解

作者: AxeChen | 来源:发表于2016-10-08 19:17 被阅读3240次

一个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_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"
可以参考:
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”对应的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)+"");
  ta.recycle();
 }
//测试代码
 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'svalue: 30.0
10-08 18:07:39.536 6313-6313/com.mg.axe.androiddevelop I/attrTwo'svalue: 1

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

运行程序之后可以看到获取到了值。但是获取到的值有些疑问:attrone设置的为10dp,为什么获取到的值是30呢?因为getDimension()方法中将dp转化成了px。使用测试代码证明了这个想法,源码中也可以看出。
源码中的 TypedValue.complexToDimension方法就是转化的代码,自定义控件时经常需要将其他格式值转为px不妨看看这里的源码。
注意:比较低的Android版本可能不会自动将dp转化为px。这里的dp2px()方法里面的TypedValue.applyDimension()是单位转化的方法,可以兼容所有Android版本,实际开发遇到单位需要转化时无论系统是否自动将dp转为px都应调用此方法用来兼容低版本。

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

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


编译无法通过的Log

e、参考的blog
http://www.jianshu.com/p/2c566331a71d
http://www.jianshu.com/p/dd79220b47dd

相关文章

  • Android 自定义控件属性

    Android 深入理解Android中的自定义属性 1. 自定义一个CustomView(extends Vie...

  • Android学习感悟之属性动画

    本篇包括Android属性动画的基本使用,理解插值器和估值器,自定义属性动画 简介 属性动画是Android3.0...

  • Android Theme Style Attr

    参考Attr、Style和Theme详解Android 深入理解Android中的自定义属性Android 中的T...

  • Android相关知识点博客记录

    自定义属性 Android自定义View(二、深入解析自定义属性) Android中XML的命名空间、自定义属性 ...

  • 理解values—attr文件

    attr全称attribute,意思是属性,性质的意思(个人理解),Android中的attr文件用于描述自定义v...

  • Android自定义属性的理解

    一个Android开发者总会遇到自定义控件的问题。要学会自定义控件的开发,最好的方法是将要用到的知识点一个个掌握。...

  • Android自定义View总结

    Android自定义View总结 [toc] 步骤 自定义View的属性 在View的构造方法获取我们自定义的属性...

  • Android自定义控件(一,基本原理)

    自定义控件相关目录: Android自定义控件(一,基本原理) Android自定义控件(二,自定义属性) And...

  • Android开发自定义属性

    目的 掌握Android开发中最基础的自定义属性方法,自定义:PageController属性,里面含有:mPad...

  • 自定义View范例

    自定义属性 像android:layout_width和android:padding这种以android开头的属...

网友评论

  • 653d1ebd6d6d:String attrTwo = ta.getString(R.styleable.TestView_attrtwo);
    Log.i("attrTwo's value",attrTwo);
    打印出来的结果不应该是“two” 吗?怎么是1呢?
    653d1ebd6d6d:@尘封的落叶 搜嘎。谢谢。没看到
    AxeChen:attrtwo为枚举类型,它的value为“1”

本文标题:Android自定义属性的理解

本文链接:https://www.haomeiwen.com/subject/dwwuyttx.html