attrs.xml

attrs属性问题

attrs.xml设定的自定义属性,指的是在xml布局中使用的 android:text="" 等属性。
第一步:
一、在res/values文件下定义一个attrs.xml文件.代码如下:

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

在这里插入图片描述

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="flow">
        <attr name="textColor" format="color"/>
    </declare-styleable>
</resources>

二:使用自定义属性,就需要有这么一个构造函数

private final static int H_DISTANCE = 20;
    private final static int V_DISTANCE = 20;
    private View childAt;
    private int color;


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

    public MyClass(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray array = context.obtainStyledAttributes(attrs,R.styleable.flow);
        color = array.getColor(R.styleable.flow_textColor, 0);
    }

    public MyClass(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    //创建添加方法
    public void addView(final String keys) {
        //创建布局 
        final String s = keys.toString();
        TextView textview = (TextView) View.inflate(getContext(), R.layout.item, null);
        textview.setText(s);
        textview.setTextColor(color);
        LayoutParams layoutParams = new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        textview.setLayoutParams(layoutParams);
        addView(textview);
    }

主要是: 使用自定义属性,就需要有这么一个构造函数.所以context.obtainStyledAttributes((attrs,R.styleable.flow) ;得到那个array数组
<R.styleable.flow 是 读取attrs中参数名,是以“样式名_参数名”的形式;>
color = array.getColor(R.styleable.flow_textColor, 0);
textview.setTextColor(color); 设置颜色就好了<字体大小都类似…>
<---------------------------------------------attrs.xml中的写法-------------------------------------------------------->
在这里插入图片描述
三:<MainActivity.xml布局中的写法>

在这里插入图片描述

自定义类中直接添加属性

在这里插入图片描述

四:效果展示
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值