In the process of customizing controls,
We often need to customize some properties for our controls
Now let’s briefly introduce the process
first step
Create a new attrs.xml file under values
The tags in the file are as follows
<declare-styleable name="Custom attribute tag name">
<attr name="attribute name" forma="type, string, dimension, etc."/>
</declare-styleable>
As follows
<?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>
Second step
Go to the root tab of the layout file
Knock an appns in the root tag to automatically complete this code
xmlns:appz="http://schemas.android.com/apk/res-auto"
The appz can be named arbitrarily, and the corresponding name can be entered when the control is used.
The format used is as follows:
appz: attribute name: "value"
As follows
<com.example.myattr.Mytx
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是一个自定义"
appz:textColor="#f00"
appz:textSize="30sp"
/>
third step:
Come to the constructor of the custom control class
The method has an attrs parameter
Execution method
getContext().obtainStyledAttributes(attrs, R.styleable.Custom attribute tag name);
or
getResources().obtainAttributes(attrs, R.styleable.Custom attribute tag name);
They all return a TypeArray object
The parameters are the tag name of attrs and custom attributes respectively
The TypeArray object has methods such as getInteger, which are used to return the relevant properties of the control you set in the layout file xml
Note that the parameters inside should be set with R.styleable. custom attribute tag name_attribute name
In this way, you can get the relevant values you set in the layout file
Finally, you can use these values to set the controls
As follows
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);
}