android自定义标签属性

来源:互联网 发布:数据库注册码 编辑:程序博客网 时间:2024/05/17 03:38

Android自定义标签属性

参考资料

  • Valid format values for declare-styleable/attr tags
  • Why do you have to recycle a TypedArray

实例代码

首先在attrs.xml文件中添加声明

<declare-styleable name="HeaderView">        <attr name="header_title" format="string" />        <attr name="header_left" format="reference" />        <attr name="header_right" format="reference" />        <attr name="header_right_text" format="string" />        <attr name="header_center" format="reference"/>        <attr name="header_center_type" format="string"/></declare-styleable>

然后在布局xml文件中使用

<com.bee.widget.HeaderView        xmlns:android="http://schemas.android.com/apk/res/android"        xmlns:hv="http://schemas.android.com/apk/res-auto"        android:id="@+id/hv_date_record"        android:layout_width="match_parent"        android:layout_height="50dp"        android:background="@color/bg_headerview"        hv:header_center_type="title"        hv:header_center="@string/date_record_title"        hv:header_left="@drawable/headerview_back"        hv:header_right="@drawable/headerview_message" />

最后在自定义组件中获取TypedArray, 获取从xml传递的数据

TypedArray a = context.obtainStyledAttributes(attrs,                R.styleable.HeaderView, 0, 0);int centerTitleId = a.getResourceId(R.styleable.HeaderView_header_center, -1);int left = a.getResourceId(R.styleable.HeaderView_header_left, -1);int right = a.getResourceId(R.styleable.HeaderView_header_right, -1);int center = a.getResourceId(R.styleable.HeaderView_header_center, -1);
  • 注意:xmlns:hv=”http://schemas.android.com/apk/res-auto” 可自动获取

attrs.xml中的format

  • reference
  • string
  • color
  • dimension
  • boolean
  • integer
  • float
  • fraction
  • enum
  • flag

如果不指定format属性,则默认为reference

TypedArray

  • Container for an array of values that were retrieved with obtainStyledAttributes(AttributeSet, int[], int, int) or obtainAttributes(AttributeSet, int[]). Be sure to call recycle() when done with them. The indices used to retrieve values from this structure correspond to the positions of the attributes given to obtainStyledAttributes.
  • TypedArray类似于键值对的map

  • 可以使用TypedArray代替ViewHolder对ListView, GridView的Adapter的getView方法进行优化

0 0