Android自定义控件——自定义属性

Android自定义控件——自定义属性,第1张

Android自定义控件——自定义属性

自定义属性
  • 自定义属性是什么?
  • 实现

自定义属性是什么?

自定义属性指用户定义的关于控件的属性,可在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);
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5687641.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存