自定义控件属性的获取

在资源文件目录下新建attrs.xml文件,声明需要的属性

<?xml version="1.0" encoding="utf-8"?>

<resources><!-- resource是跟标签,可以在里面定义若干个declare-styleable -->
    <declare-styleable name="custom_view"><!-- name定义了变量的名称 -->
        <attr name="custom_color" format="color|reference"></attr> <!-- 定义对应的属性,name定义了属性的名称 -->
        <attr name="custom_size" format="dimension|reference"></attr> <!--每一个发生要定义format指定其类型,类型包括 
          reference   表示引用,参考某一资源ID
          string   表示字符串
          color   表示颜色值
          dimension   表示尺寸值
          boolean   表示布尔值
          integer   表示整型值
          float   表示浮点值
          fraction   表示百分数
          enum   表示枚举值
          flag   表示位运算
        -->
  </declare-styleable>

 

第二步: 在构造方法中获取自定义属性,  通过context.obtainStyledAttributes(attrs, R.styleable.custom_view)方法

 

public class CustomTextView extends TextView {
    private int textSize;//自定义文件大小
    private int textColor;//自定义文字颜色

    //自定义属性,会调用带两个对数的构造方法
    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.custom_view);//TypedArray属性对象
        textSize = ta.getDimensionPixelSize(R.styleable.custom_view_custom_size, 20);//获取属性对象中对应的属性值 
        textColor = ta.getColor(R.styleable.custom_view_custom_color, 0x0000ff);
        setColorAndSize(textColor, textSize);//设置属性
        ta.recycle();
    }

    public CustomTextView(Context context) {
        super(context);
    }

    private void setColorAndSize(int textColor, int textSize) {
        setTextColor(textColor);
        setTextSize(textSize);
    }

}

 

参考:  Android自定义控件属性

 

转载于:https://www.cnblogs.com/huyang011/p/7617419.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值