自定义视图属性

1.自定义一个继承View或者View子类的视图类(实现含有AttributeSet的构造函数)

import android.util.AttributeSet;
import android.view.View;

/**
 * Created by 小新 on 2016/3/10.
 */
public class MyTextView extends View {
    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        
    }
}

2.编写values/attrs.xml(编写自定义属性)声明两个标签  declare-styleable(name)  和attr(name  format)

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

3.在布局文件中使用自定义的属性(注意前面要加上命名空间 AS下只要输入自定义属性,他会自动提示namespace)

<com.example.myapplication.MyTextView
    app:rect_color="#cc99cc"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

4.在自定义视图类中的构造方法通过TypeArray获取

public class MyTextView extends View {
    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.MyTextView);
        int color = typedArray.getColor(R.styleable.MyTextView_rect_color,0x0000ff);
        setBackgroundColor(color);
        //记得回收资源
        typedArray.recycle();
    }
}
加深理解

1.AttributeSet可以获取布局文件中定义的所有属性的key和value,但是拿到的是它的ID  而通过TypedArray拿到的是解析后的ID

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值