Android自定义属性

来源:互联网 发布:sql server 1326错误 编辑:程序博客网 时间:2024/06/14 23:31

参考博客:鸿洋老师的博客http://blog.csdn.net/lmj623565791/article/details/45022631

1.自定义的步骤:

a.自定义一个ArcMenu extends ViewGroup;

b.在values/attr.xml中自定义属性,定义styleable和item属性;

 <!--位置信息-->    <attr name="position">        <enum name="left_top" value="0"  />        <enum name="left_bottom" value="1"  />        <enum name="right_top" value="2"  />        <enum name="right_bottom" value="3"  />    </attr>    <!--半径尺寸-->    <attr name="radius" format="dimension"/>    <declare-styleable name="ArcMenu">        <attr name="position"/>        <attr name="radius"/>    </declare-styleable>

其中format的是radius所对应的取值类型,常见的format的取值类型有string,color,integer,enum,demension,reference,fraction,float,boolean,flag。declare-styleable 中的名字一般用自定义的控件名命名name=”ArcMenu”。标签声明了使用自定义的属性,并通过name属性来确定引用的名称。通过标签来声明具体的自定义的属性如这里面可以自定义字体的大小,颜色,背景等。并且是通过format属性来制定属性的类型。有些属性可以是颜色属性,也可以是引用属性。比如按钮的背景,可制定具体的颜色,也可以制定一张图片,所以就要用“|”来分开不同的属性—“reference|color”。

c.在布局文件中使用自定义的属性,要注意重新定义命名空间;

//命名空间xmlns:keke="http://schemas.android.com/apk/res-auto" <com.best.keke.arcmenu.view.ArcMenu        android:id="@+id/arcmenu"        android:layout_width="match_parent"        android:layout_height="match_parent"        keke:position="right_bottom"        keke:radius="180dp">  </com.best.keke.arcmenu.view.ArcMenu>

d.在ArcMenu的构造方法中通过TypedArray获取到值

   系统提供了TypedArray 这样的数据结构来获取到自定义的属性集。 public ArcMenu(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        // 获取到自定义的属性值        TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ArcMenu, defStyleAttr, 0);        int pos = typedArray.getInt(R.styleable.ArcMenu_position, POS_RIGHT_BOTTOM);         typedArray.recycle();    }

这里需要注意的是当获取完所有的属性值后,需要调用TypedArray 的recyle方法来完成资源的回收,避免重新创建的时候的错误。

0 0
原创粉丝点击