Radio只能存放一个Text,现在想多加一个属性Value
需要新定义一个Myradiobutton类,继承RadioButton类,并添加Value属性及getset方法
因为要在XML中设置属性,所以要添加res/Values/attrs.xml文件,声明这个属性
attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RadioButton"><!-- 控件名称-->
<attr name="value" format="string"/><!-- 属性名称,类型-->
</declare-styleable>
</resources>
然后在Myradiobutton构造方法中获取xml中的value值赋给RadioButton
public MyRadioButton(Context context, AttributeSet attrs) {
super(context, attrs);
try {
/**
* 跟values/attrs.xml里面定义的属性绑定
*/
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.RadioButton);
this.mValue = a.getString(R.styleable.RadioButton_value);
a.recycle();
} catch (Exception e) {
e.printStackTrace();
}
setOnCheckedChangeListener(this);
}
这样在布局文件中就能设置RadioButon的Value值了 xmlns:fsms="http://schemas.android.com/apk/res/com.sinxiao.myview"
这句是给添加命名空间fsms,com.sinxiao是包名,myview是类名
可以用fsms:Value=“String” 赋值了
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fsms="http://schemas.android.com/apk/res/com.sinxiao.myview"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.sinxiao.view.MyRadioGroup
android:id="@+id/radPayOrNot"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<com.sinxiao.view.MyRadioButton
android:id="@+id/isPayDepositTrue"
fsms:value="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/yes"
android:textSize="18sp" />
<com.sinxiao.view.MyRadioButton
android:id="@+id/isPayDepositFalse"
fsms:value="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/no"
android:textSize="18sp" />
</com.sinxiao.view.MyRadioGroup>
</LinearLayout>
新建一个类MyradioGroup,继承类RadioGroup
在里面新加一个变量value,
当点击某一个选项时,改变radioGroup中value为点击的Radio的value值
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { MyRadioGroup group = (MyRadioGroup) getParent(); group.setTheValue(this.getValue()); Log.d("-------Main", "the new value is ===>"+this.getValue()); }
在GroupRadio中当发生改变时根据GroupRadio中的value值,改变radio的点击状态
private void setChildValue() { int n = this.getChildCount(); Log.d(tag, "the n is " + n); for (int i = 0; i < n; i++) { MyRadioButton radio = (MyRadioButton) this.getChildAt(i); if (radio.getValue().equals(this.mValue)) { radio.setChecked(true); } else { radio.setChecked(false); } } }
获取当前选择的radio的值@Override public void onCheckedChanged(RadioGroup group, int checkedId) { setChildValue(); }
// 获取子类的值 private void getChildValue() { int n = this.getChildCount(); for (int i = 0; i < n; i++) { MyRadioButton radio = (MyRadioButton) this.getChildAt(i); if (radio.isChecked()) { this.mValue = radio.getValue(); } } }