【发布时间】:2018-04-09 19:47:31
【问题描述】:
我在列表视图中设置了 3 个 ToggleButton。当一个按钮被选中时,另外两个将被取消选中。但它不工作。当我检查一个按钮时,其他两个按钮未从其他行中选中。但我想取消选中该行中的其他两个按钮。
public class MyListAdapter extends ArrayAdapter<Salat>{
private Activity context;
private Salat[] salat;
TextView salatName;
ToggleButton prayedButton;
ToggleButton prayedLateButton;
ToggleButton missedButton;
final DB db = new DB(context);
public MyListAdapter(@NonNull Context context, Salat[] salat) {
super(context, R.layout.salat_listview, salat);
this.context = (Activity) context;
this.salat = salat;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listview = inflater.inflate(R.layout.salat_listview, null, true);
salatName = (TextView) listview.findViewById(R.id.salat_name);
prayedButton = (ToggleButton) listview.findViewById(R.id.prayed_button);
prayedLateButton = (ToggleButton) listview.findViewById(R.id.prayed_late_button);
missedButton = (ToggleButton) listview.findViewById(R.id.missed_button);
salatName.setText(getItem(position).getName());
prayedButton.setOnCheckedChangeListener(buttonListener);
prayedLateButton.setOnCheckedChangeListener(buttonListener);
missedButton.setOnCheckedChangeListener(buttonListener);
prayedButton.setTag(position);
prayedLateButton.setTag(position);
missedButton.setTag(position);
return listview;
}
CompoundButton.OnCheckedChangeListener buttonListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(compoundButton.getId() == prayedButton.getId()){
compoundButton.setChecked(b);
prayedLateButton.setChecked(!b);
missedButton.setChecked(!b);
}
else if(compoundButton.getId() == prayedLateButton.getId()){
compoundButton.setChecked(b);
prayedButton.setChecked(!b);
missedButton.setChecked(!b);
}
else if(compoundButton.getId() == missedButton.getId()){
compoundButton.setChecked(b);
prayedButton.setChecked(!b);
prayedLateButton.setChecked(!b);
}
}
};
}
我知道这是错误的方法。但是我怎样才能在 listView 中做到这一点。也许没有办法用getTag() 或位置来解决这个问题。
【问题讨论】:
-
您的问题不清楚。您要取消选中列表视图中的所有项目还是仅取消选中该特定项目?
-
没有。当从一行中选中一个按钮时,其他两个按钮将从该行中取消选中。请看截图。
-
那么你的方法是正确的。 getView() 方法一次只能处理 1 个项目
-
你能给我一个解决方案或其他方法吗?
-
试试我给出的答案
标签: android listview android-studio listener