ListView 中显示自定义单选列表,实现单选效果(左文字,右图片)

时间:2021-06-11 19:31:53

有时候项目中会遇到各种各样的设计与需求,把这两天在工作中涉及到的有点小问题的总结下

1.单选不互斥

public class Single_choice_adapter extends BaseAdapter {
private Context context;
private String[] list;
private HashMap<String, Boolean> states = new HashMap<String, Boolean>();// 用于记录每个RadioButton的状态,并保证只可选一个


private TextView test;


onRadioButtonClickListners radioButtonClickListner;


public Single_choice_adapter(Context context, String[] strings,
TextView test) {
super();
this.context = context;
this.list = strings;
this.test = test;
}


@Override
public int getCount() {
return list.length;
}


@Override
public Object getItem(int arg0) {
return list[arg0];
}


@Override
public long getItemId(int arg0) {
return arg0;
}


private class ViewHolder {
private TextView name;


private LinearLayout lin;
private RadioButton radioButton;
}


@Override
public View getView(final int position, View convertView, ViewGroup arg2) {
final ViewHolder viewHolder;
if (convertView == null) {


convertView = LayoutInflater.from(context).inflate(
R.layout.single_choice, arg2, false);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) convertView
.findViewById(R.id.single_name);


viewHolder.lin = (LinearLayout) convertView.findViewById(R.id.add);
convertView.setTag(viewHolder);


} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final RadioButton radioButton = (RadioButton) convertView
.findViewById(R.id.radioBtn);
viewHolder.radioButton = radioButton;
viewHolder.name.setText(list[position]);
viewHolder.radioButton.setTag(position);
viewHolder.radioButton.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View arg0) {


for (String key : states.keySet()) {
states.put(key, false);


}
states.put(String.valueOf(position), radioButton.isChecked());
Single_choice_adapter.this.notifyDataSetChanged();
test.setText(list[position]);
int position = (Integer) viewHolder.radioButton.getTag();
radioButtonClickListner.onRadioButtonCallBacks(position, arg0);
}
});


boolean res = false;
if (states.get(String.valueOf(position)) == null
|| states.get(String.valueOf(position)) == false) {
res = false;
states.put(String.valueOf(position), false);
} else
res = true;


viewHolder.radioButton.setChecked(res);
return convertView;


}


public void setRadioButtonCallBacks(
onRadioButtonClickListners radioButtonClickListners) {


this.radioButtonClickListner = radioButtonClickListners;
}


public interface onRadioButtonClickListners {
void onRadioButtonCallBacks(int position, View v);
}
}