1.预习:
2.在attrs.xml中创建自定义属性
Paste_Image.png其中:
- 属性集合的名称任意,这里是"anything"
- 单个自定义属性的名称也是任意的,如"attr_str"
- 属性的值类型,即format值请参考Android自定义控件之自定义属性 format详解
3.在自定义View中获取xml中设置的自定义属性
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自动寻找自定义属性,只需导入
xmlns:app="http://schemas.android.com/apk/res-auto" - 为自定义View设置自定义属性
<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"/>
网友评论