Android自定义属性

参考博客:鸿洋老师的博客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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值