listview含有radiobtn,點選實現單選
阿新 • • 發佈:2019-01-27
注意事項:
首先自定義ChoiceView類實現Checkable介面
public class ChoiceView extends FrameLayout implements Checkable{
private TextView mTextView;
public RadioButton mRadioButton;
public ChoiceView(Context context) {
super(context);
View.inflate(context, R.layout.listview_installment_item, this );
mTextView = (TextView) findViewById(R.id.tv_qishu);
mRadioButton = (RadioButton) findViewById(R.id.radiobtn);
}
public void setText(String text) {
mTextView.setText(text);
}
@Override
public void setChecked(boolean checked) {
mRadioButton.setChecked(checked);
}
@Override
public boolean isChecked() {
return mRadioButton.isChecked();
}
@Override
public void toggle() {
mRadioButton.toggle();
}
}
單選item的佈局listview_installment_item,我的佈局程式碼用了弘陽的AutoRelativeLayout庫,自己可以修改成安卓自己的RelativeLayout,另外需要注意的是radiobutton的android:clickable=”false”
android:focusable=”false”
android:focusableInTouchMode=”false”
這三個屬性必須加,要不會報錯
<?xml version="1.0" encoding="utf-8"?>
<com.lixue.aibei.autolayoutlib.AutoLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:descendantFocusability="blocksDescendants"
android:layout_height="match_parent">
<com.lixue.aibei.autolayoutlib.AutoRelativeLayout
android:layout_width="match_parent"
android:layout_marginLeft="20px"
android:layout_marginRight="20px"
android:layout_height="80px">
<TextView
android:id="@+id/tv_qishu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="3期"
android:textColor="@color/text_gray"
/>
<RadioButton
android:id="@+id/radiobtn"
android:layout_width="54px"
android:layout_height="54px"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:button="@drawable/selector_radiobtn"
/>
</com.lixue.aibei.autolayoutlib.AutoRelativeLayout>
</com.lixue.aibei.autolayoutlib.AutoLinearLayout>
在activty的oncreate中,寫如下程式碼
for(int i=0;i<5;i++){
PeriodandRateBean periodandRateBean=new PeriodandRateBean();
periodandRateBean.setLimit(i+"");
periodandRateBeanList.add(periodandRateBean);
}
ListAdapter adapter = new ArrayAdapter<PeriodandRateBean>(SocialsecurityLoanActivity.this, R.layout.listview_installment_item, periodandRateBeanList) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ChoiceView view;
if(convertView == null) {
view = new ChoiceView(SocialsecurityLoanActivity.this);
} else {
view = (ChoiceView)convertView;
}
view.setText(periodandRateBeanList.get(position).getLimit()+"個月");
return view;
}
};
//這個屬性可以設定預設選中的項
listView.setItemChecked(fenqi_select_pos, true);
PeriodandRateBean 這個bean是自己定義的,依據自己的需求來寫,我的效果最後實現的是這樣,這裡參考了稀土掘金大神的帖子,大家可以去看一下