在一些自定义view中我们往需要预先定义一些默认属性,这些参数常常跟view绑定的,因而在定义view的布局文件中添加这些属性就显得尤为有价值。整个过程分三步:
1.定义declare-styleable,用于TypedArray来绑定对于的参数,在此需要在value目录里面新建文件:attrs.xml
- <resources> 点击打开链接
- <declare-styleable name="Def">
- <!-- The first screen the workspace should display. -->
- <attr name="num" format="integer" />
- <attr name="length" format="integer" />
- </declare-styleable>
- </resources>
2.布局文件中配置控件,这里包含xml声明,还有对应的属性值
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- <span style="color: #ff0000;">xmlns:test="http://schemas.android.com/apk/res/com.yuhua.test"</span>
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello" />
- <span style="color: #ff0000;"> <com.yuhua.test.LocalView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- test:num ="3"
- test:length="5"
- /></span>
- </LinearLayout>
3. 通过映射获取配置的属性
- public class LocalView extends View {
- private static final String TAG = "LocalView";
- public LocalView(Context context) {
- super(context);
- }
- public LocalView(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- }
- public LocalView(Context context, AttributeSet attrs) {
- super(context, attrs);
- TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Def);
- Log.i(TAG, a.getInt(R.styleable.Def_length, 0) + "===" + a.getInt(R.styleable.Def_num, 0));
- }
- }