我有一個listivew自定義arrayadapter和自定義佈局,它有一個複選框。 我想讓這個listview只啓用一個複選框,但我不知道我該怎麼做。listview with checkbox single clickable
這是我的適配器,但檢查和取消選中不工作正常。請任何人舉例。
public class gremioAdapter extends ArrayAdapter<Gremio> {
Context context;
int layoutResourceId;
ArrayList<Gremio> data = null;
protected String comentarioAlEdiText;
public gremioAdapter(Context context, int layoutResourceId, ArrayList<Gremio> data)
{
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
public void updateDataSet(Gremio objetoGremioAnadir) {
this.data.add(objetoGremioAnadir);
notifyDataSetChanged();
}
public void updateDataSet(Gremio objetoGremioAnadir, int posicion) {
this.data.add(posicion, objetoGremioAnadir);
notifyDataSetChanged();
}
public void updateDataSet(String comentario, int posicion) {
this.data.get(posicion).comentario = comentario;
notifyDataSetChanged();
}
public void updateDataSet() {
notifyDataSetChanged();
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
GremioHolder holder = null;
final GremioHolder h2 = holder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layoutResourceId, parent, false);
holder = new GremioHolder();
holder.tvGremio = (TextView) row.findViewById(R.id.tvGremio);
holder.cbActivo = (CheckBox) row.findViewById(R.id.cbGremioActivo);
holder.tvComentario = (TextView) row.findViewById(R.id.tvComentario);
row.setTag(holder);
}
else {
holder = (GremioHolder) row.getTag();
}
Gremio gremioFinal = data.get(position);
holder.tvGremio.setText(gremioFinal.literal);
holder.tvComentario.setText(gremioFinal.comentario);
if (data.get(position).getActivo().equals("1")) {
holder.cbActivo.setChecked(true);
}
else {
holder.cbActivo.setChecked(false);
}
holder.cbActivo.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
if (data.get(position).activo.equals("0"))
h2.cbActivo.setChecked(true);
if (data.get(position).activo.equals("1"))
h2.cbActivo.setChecked(false);
}
});
holder.cbActivo.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
for (int i = 0; i < data.size(); i++) {
data.get(i).activo = "0";
}
data.get(position).activo = "1";
}
if (isChecked) {
for (int i = 0; i < data.size(); i++) {
data.get(i).activo = "0";
}
}
notifyDataSetChanged();
}
});
return row;
}
public class GremioHolder {
TextView tvGremio;
CheckBox cbActivo;
TextView tvComentario;
}
}
}
你的意思是說你想讓它互斥嗎?即,如果您選中一個複選框,則應該取消選中其他複選框? – Shubhayu 2012-07-16 09:26:51
使用切換按鈕,而不是複選框,並創建選擇器xml文件在drawable folder.rather比使用arrayAdapter使用BaseAdapter,這將很容易實現 – AkashG 2012-07-16 09:30:32
@Shubhayu是的,如果我檢查一個,其他人被取消選中。 – rbrlnx 2012-07-16 09:34:31