1.預(yù)習(xí):
2.在attrs.xml中創(chuàng)建自定義屬性

Paste_Image.png
其中:
- 屬性集合的名稱任意,這里是"anything"
- 單個自定義屬性的名稱也是任意的,如"attr_str"
- 屬性的值類型,即format值請參考Android自定義控件之自定義屬性 format詳解
3.在自定義View中獲取xml中設(shè)置的自定義屬性
public class CustomTextView extends TextView {
public CustomTextView(Context context) {
this(context, null);
}
public CustomTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.anything);
String attr_str = typedArray.getString(R.styleable.anything_attr_str);
Integer attr_integer = typedArray.getInteger(R.styleable.anything_attr_integer, -1);
Drawable attr_backgroud = typedArray.getDrawable(R.styleable.anything_attr_background);
int attr_color = typedArray.getColor(R.styleable.anything_attr_color, 0);
boolean attr_boolean = typedArray.getBoolean(R.styleable.anything_attr_boolean, false);
setText(attr_str + ", " + attr_integer + ", " + attr_boolean);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN ) {//>=16
setBackground(attr_backgroud);
} else {
setBackgroundDrawable(attr_backgroud);
}
setTextColor(attr_color);
}
}
4.在布局文件中為自定義屬性賦值
- 讓Gradle自動尋找自定義屬性,只需導(dǎo)入
xmlns:app="http://schemas.android.com/apk/res-auto" - 為自定義View設(shè)置自定義屬性
<along.chen.com.myview.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:attr_str="It's just a next beginning"
app:attr_boolean="true"
app:attr_color="#f00a"
app:attr_background="@drawable/shape_backgroud"
android:padding="15dip"
android:text="@string/app_name"/>