栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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);
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/687116.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号