
- 自定义属性是什么?
- 实现
自定义属性指用户定义的关于控件的属性,可在xml布局文件中直接应用并获取
实现在res/values下新建attrs.xml,如下在一个declare-styleable标签下定义了2个arr标签
在自定义控件MyView中使用自定义属性my:attr1和my:attr2,使用前应该申明命名空间xmlns:my="http://schemas.android.com/apk/res-auto"
在自定义控件中获取属性的值,在构造方法中通过TypedArray获取
public class MyView extends LinearLayout {
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.My_style);
boolean attr1 = ta.getBoolean(R.styleable.My_style_attr1, true);
int attr2 = ta.getInteger(R.styleable.My_style_attr2, 0);
ta.recycle();
Log.d("test", "attr1=" + attr1);
Log.d("test", "attr1=" + attr2);
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)