自定义之前我们首先了解一下,view的构造函数,因为自定义属性往往在子类中获取并使用。
/**
* Code中创建View时使用的构造方法
* Simple constructor to use when creating a view from code.
*/
View(Context context)
/**
* 绘制Xml中View时使用的构造方法
* Constructor that is called when inflating a view from XML.
*/
View(Context context,AttributeSet attrs)
/**
* Perform inflation from XML and apply a class-specific base style from a theme attribute.
*/
View(Context context, AttributeSet attrs, int defStyleAttr)
/**
* Perform inflation from XML and apply a class-specific base style from a theme attribute or style resource.
*/
View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
在派生的时候往往需要重写第二个构造函数,记住访问属性:public
。
实现自定义属性步骤:
1.在values/attrs.xml
中增加新增属性(如果没有则新建attrs.xml,New->XML->values XML File)
2.在xml中应用自定义的属性(自定义属性任何类都可以使用)
3.获取并使用属性。
新增属性:dog_name,dog_weight
<?xml version="1.0" encoding="utf-8"?>
<resources>
//自定义属性名称空间:name=dog,包含属性:name,weight
<declare-styleable name="dog">
<attr name="name" format="string" />
<attr name="weight" format="integer" />
</declare-styleable>
</resources>
xml中使用自定义属性:name,weight
引用的时候根目录一定要包含:xmlns:app="http://schemas.android.com/apk/res-auto"
或者自定义空间xmlns:dog="http://schemas.android.com/apk/res/com.example.qwe"
。此处我们以app为准。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
//如果这里使用了dog,那么下面就不是app:name,而是dog:name
//xmlns:dog="http://schemas.android.com/apk/res/com.example.qwe"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:fitsSystemWindows="true">
<com.example.qwe.DogView
android:layout_width="match_parent"
android:layout_height="10dp"
app:name="hellow"
app:weight="10"/>
</LinearLayout>
view获取并使用属性
public class DogView extends TextView {
private final static String TAG = "DogView";
public DogView(Context context, AttributeSet attrs){
super(context,attrs);
TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.dog);
int weight = ta.getInteger(R.styleable.dog_weight,0);
String name = ta.getString(R.styleable.dog_name);
Log.i(TAG, "DogView name:"+name+",weight:"+weight);
}
}
使用系统属性作为自定义属性
eg:android:text
,因为是系统属性,所以不需要指定format类型。
<attr name="android:text" />
xml 直接使用系统定义属性,进行赋值:
<com.example.qwe.DogView
android:text="MyDog"
android:layout_width="match_parent"
android:layout_height="10dp"
dog:name="hellow"
dog:weight="10"/>
获取并使用
String text = ta.getString(R.styleable.dog_android_text);
参考博客:
https://blog.youkuaiyun.com/lmj623565791/article/details/45022631
https://www.jianshu.com/p/7399d2188b6e