您的位置:首页 > 移动开发 > Android开发

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

2016-06-01 16:40 435 查看
在一些自定义view中我们往需要预先定义一些默认属性,这些参数常常跟view绑定的,因而在定义view的布局文件中添加这些属性就显得尤为有价值。整个过程分三步:

1.定义declare-styleable,用于TypedArray来绑定对于的参数,在此需要在value目录里面新建文件:attrs.xml

Java代码


<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声明,还有对应的属性值

Java代码


<?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. 通过映射获取配置的属性

Java代码


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));

}

}

转自:http://geyubin.iteye.com/blog/1562868
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  自定义view 传参