1. 声明declare-styleable属性在attrs.xml文件里面
<?xml version="1.0" encoding="UTF-8"?> <resources> <declare-styleable name="MyView"> <attr name="color" format="color"/> <attr name="size" format="dimension" /> <attr name="Oriental"> <enum name="Horizontal" value="1"></enum> <enum name="Vertical" value="0"></enum> </attr> </declare-styleable> </resources>
2.在布局文件里面添加属性声明: xmlns:test="http://schemas.android.com/apk/res/com.yuhua.test" 其中 test是控件属性的前缀名称,而com.yuhua.test是工程包名
这里还有另外一种添加属性声明的方式:
xmlns:test="http://schemas.android.com/apk/res-auto"
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:test="http://schemas.android.com/apk/res/com.yuhua.test" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <com.yuhua.test.MyTextView android:id="@+id/tv_test" android:layout_width="fill_parent" android:layout_height="wrap_content" test:color="#ff0000" test:size="23sp" test:Oriental="Horizontal" android:text="@string/hello" /> </LinearLayout>
3.在自定义组件的java代码中获取属性,并进行逻辑处理
public class MyTextView extends TextView {
private static final String TAG = "MyTextView";
public MyTextView(Context context) {
super(context);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typeArray = context.obtainStyledAttributes(attrs, R.styleable.MyView);
int color = typeArray.getColor(R.styleable.MyView_color, Color.BLACK);
float size = typeArray.getDimension(R.styleable.MyView_size, 12.0f);
int oriental = typeArray.getInt(R.styleable.MyView_Oriental, 0);
Log.i(TAG, "===the defOriental:" + oriental);
this.setTextColor(color);
this.setTextSize(size);
typeArray.recycle();
}
}