有时做开发的时候,需要将一些属性值绑定到控件中,这样当用户选择某个控件时,我们可以直接从所选控件中获取所需要的值,这样开发也就容易一点了。
下面我们开始来说一下基本的步骤:
1:在res/values/attrs.xml文件中定义要添加的属性值
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyRadioButton">
<attr name="value" format="string"/>
</declare-styleable>
</resources>
2:创建自定义的控件类:
public class MyRadioButton extends RadioButton { public MyRadioButton(Context context, AttributeSet attrs) { super(context, attrs); //从attrs.xml获取自定义的控件属性 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyRadioButton); 从attrs.xml获取自定义的value属性(控件属性名称+“_” + 自定义的属性名称) this.m_value = a.getString(R.styleable.MyRadioButton_value); a.recycle(); } public String getM_value() { return m_value; } public void setM_value(String mValue) { m_value = mValue; } //自定义属性 private String m_value; }
3:在res/layout/main.xml 窗口中创建自定义的控件
<?xml version="1.0" encoding="utf-8"?>
<!-- xmlns:cs="http://schemas.android.com/apk/res/com.draw" 为自定义控件指定命名空间
com.draw: 取AndroidManifest.xml中 package="com.draw" 属性值
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cs="http://schemas.android.com/apk/res/com.draw"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<!-- cs:value="value" 为自定义的属性赋值 -->
<com.draw.MyRadioButton android:id="@+id/rdTest" cs:value="checked"
android:text="hello" android:layout_height="wrap_content" android:layout_width="wrap_content"/>
</LinearLayout>