gpt4 book ai didi

Android:CursorAdapter、ListView 和 CheckBox

转载 作者:IT老高 更新时间:2023-10-28 23:26:26 24 4
gpt4 key购买 nike

我的 ListView 有我自己的布局和 CustomCursorAdapter。每行都有自己的复选框。所以......绝对清楚,在滚动期间,复选框会失去它们的状态。我找到的唯一东西是Android save Checkbox State in ListView with Cursor Adapter但那里没有答案。还有一个问题。我的CustorArrayAdapter 也有同样的问题。我使用 SparseBooleanArray 解决了这个问题,以保持复选框状态。它工作正常,但每次滚动都会调用 onCheckedChanged。这正常吗?这笔交易是我的 ListView 描述了警报元素和定期调用(onCheckedChanged)启动/停止警报。很多不必要的操作。

最佳答案

我的 ListViewCheckBox 有类似的问题,我做了什么来解决这个问题:

  • 创建一个 bool 对象的 ArrayList 来存储每个 CheckBox 的状态
  • 将ArrayList项初始化为默认值false,表示还没有选中CheckBox。
  • 当您单击复选框时。设置 Checked/Unchecked 状态检查并将该值存储在 ArrayList 中。
  • 现在使用 setChecked() 方法将该位置设置为 CheckBox。

查看此代码段:

public class MyDataAdapter extends SimpleCursorAdapter {
private Cursor c;
private Context context;
private ArrayList<String> list = new ArrayList<String>();
private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();

// itemChecked will store the position of the checked items.

public MyDataAdapter(Context context, int layout, Cursor c, String[] from,
int[] to) {
super(context, layout, c, from, to);
this.c = c;
this.context = context;

for (int i = 0; i < this.getCount(); i++) {
itemChecked.add(i, false); // initializes all items value with false
}
}

public View getView(final int pos, View inView, ViewGroup parent) {
if (inView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inView = inflater.inflate(R.layout.your_layout_file, null);
}

final CheckBox cBox = (CheckBox) inView.findViewById(R.id.bcheck); // your
// CheckBox
cBox.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

CheckBox cb = (CheckBox) v.findViewById(R.id.your_checkbox_id);

if (cb.isChecked()) {
itemChecked.set(pos, true);
// do some operations here
} else if (!cb.isChecked()) {
itemChecked.set(pos, false);
// do some operations here
}
}
});
cBox.setChecked(itemChecked.get(pos)); // this will Check or Uncheck the
// CheckBox in ListView
// according to their original
// position and CheckBox never
// loss his State when you
// Scroll the List Items.
return inView;
}}

关于Android:CursorAdapter、ListView 和 CheckBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4803756/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com