android在布局文件中自定义参数并在初始化时获取

在一些自定义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"
    xmlns:test="http://schemas.android.com/apk/res/com.yuhua.test"
    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" />
     <com.yuhua.test.LocalView 
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         test:num ="3"
         test:length="5"
         />
</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));
	}
}
 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值