加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

(总结)自定义属性

发布时间:2020-12-16 05:56:55 所属栏目:百科 来源:网络整理
导读:自定义 View 的自定义属性 1. 在 values文件中,新建 attrs.xml 文件(如果原来没有),内容大致是这样, ?xmlversion="1.0"encoding="utf-8"? resources !-- 自定义圆角 imageview 属性 -- declare-styleablename="RoundImageView" attrname="xhradius"form

自定义View的自定义属性

1.values文件中,新建attrs.xml文件(如果原来没有),内容大致是这样,

<?xmlversion="1.0"encoding="utf-8"?>

<resources>

<!--自定义圆角imageview属性-->

<declare-styleablename="RoundImageView">

<attrname="xhradius"format="dimension"></attr>

<attrname="xhtype">

<enumname="fillet"value="0"></enum>

<enumname="round"value="1"></enum>

</attr>

</declare-styleable>

</resources>

解读一下,<declare-styleablename="RoundImageView">申明一个控件

,其中name="RoundImageView"是定义这个控件的那个java类的名称.

<attrname="xhradius"format="dimension"></attr>就是自定义的一条属性,申明了属性的名称和属性的类型。

2.在自定义Viewjava类中,使用几个构造方法来接收自定义的值。如

//半径

privatefloatradius=0;

//类型

privateinttype;

publicRoundImageView(Contextcontext,AttributeSetattrs){

this(context,attrs,0);//没有这个方法就会出错。没有这句话就会读不到值

}

publicRoundImageView(Contextcontext,AttributeSetattrs,intdefStyleAttr){

super(context,defStyleAttr);

TypedArraytypedArray=context.getTheme().obtainStyledAttributes(attrs,R.styleable.RoundImageView,defStyleAttr,0);

radius=typedArray.getDimension(R.styleable.RoundImageView_xhradius,0);//默认半径0

type=typedArray.getInt(R.styleable.RoundImageView_xhtype,0);//默认圆角类型

typedArray.recycle();

paint=newPaint();

}

3.在布局文件中引用。并设置属性。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读