自定义控件过程中,
我们往往需要给自己的控件来自定义一些属性
现在就来大概介绍下流程
第一步
values下新建attrs.xml文件
文件里标签如下
<declare-styleable name="自定义属性标签名">
<attr name="属性名字" forma="类型,有string,dimension等"/>
</declare-styleable>
如下所示
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--自定义属性-->
<declare-styleable name="myattrs"><!--这里是自定义属性标签名-->
<attr name="textSize" format="dimension"/><!--这里是自定义属性名1-->
<attr name="textColor" format="color"/><!--这里是自定义属性名2-->
</declare-styleable>
</resources>
第二步
来到布局文件的根标签下
在根标签敲一个appns,自动补全这段代码
xmlns:appz="http://schemas.android.com/apk/res-auto"
其中appz是可以自己随便命名的的,控件使用时输入对应的名字即可
使用的格式如下:
appz:属性名字:"数值"
如下所示
<com.example.myattr.Mytx
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是一个自定义"
appz:textColor="#f00"
appz:textSize="30sp"
/>
第三步:
来到自定义控件的类的构造方法中
该方法有一个attrs参数
执行方法
getContext().obtainStyledAttributes(attrs, R.styleable.自定义属性标签名);
或者
getResources().obtainAttributes(attrs, R.styleable.自定义属性标签名);
他们都会返回一个TypeArray对象
参数分别是attrs和自定义属性的标签名
TypeArray对象有getInteger等方法,用来返回你在布局文件xml中设置的控件的相关属性
注意,里面的参数要用R.styleable.自定义属性标签名_属性名字来设置
这样,就可以得到你在布局文件中设置的相关数值
最后你用这些数值对控件进行设置即可
如下所示
public Mytx(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.myattrs);
float anInt = typedArray.getDimension(R.styleable.myattrs_textSize, 10);
int anColor = typedArray.getColor(R.styleable.myattrs_textColor, Color.BLACK);
setTextSize(anInt);
setTextColor(anColor);
}