gpt4 book ai didi

java - 使用自定义适配器获取已检查的项目

转载 作者:行者123 更新时间:2023-11-30 10:58:41 24 4
gpt4 key购买 nike

我有带有自定义适配器的 ListView 。此 ListView 的每个元素都有复选框。标准函数 .getCheckedItemPositions() 不起作用。

创建时:

  final String[] words = new String[] {
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"
};


MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, words);
listView.setAdapter(adapter);

我的适配器:

public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
DataBaseHelper myDbHelper;
int id = 1;


public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.listitem, values);
this.context = context;
this.values = values;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

View rowView = inflater.inflate(R.layout.listitem, parent, false);
CheckBox checkBox = (CheckBox)rowView.findViewById(R.id.checkBox);
TextView newwordview = (TextView)rowView.findViewById(R.id.newwordview);


newwordview.setText("lalala");

return rowView;
}
}

这里我尝试获取选中的项目:

public void addbtnclick(View view){
int cntChoice = listView.getCount();
SparseBooleanArray sparseBooleanArray = listView.getCheckedItemPositions();

for (int i = 0; i < cntChoice; i++) {

if (sparseBooleanArray.get(i) == true) {
String a = listView.getItemAtPosition(i).toString();
myDbHelper.setadd(a, "en");
} else if (sparseBooleanArray.get(i) == false) {

}
}
}

在调试中,sparseBooleanArray 总是有 0 个项目。我该怎么办?

最佳答案

您可能应该让您的适配器成为一个可以保留其选中状态的对象列表,而不是字符串。

public class Item
{
public String title;
public boolean checked;
}

然后:

public class MySimpleArrayAdapter extends ArrayAdapter<Item>
{
@Override
public View getView(final int position, View convertView, ViewGroup parent) {

View rowView = inflater.inflate(R.layout.listitem, parent, false);
CheckBox checkBox = (CheckBox)rowView.findViewById(R.id.checkBox);
TextView newwordview = (TextView)rowView.findViewById(R.id.newwordview);

Item item = getItem(position);
newwordview.setText(item.title);
checkBox.setChecked(item.checked);


checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton view, boolean isChecked)
{
Item item = getItem(position);
item.checked = isChecked;
}
});

return rowView;
}
}

此外:出于性能原因,您真的应该在存在时重新使用 convertView。我建议查看 View 持有者模式: How can I make my ArrayAdapter follow the ViewHolder pattern?

关于java - 使用自定义适配器获取已检查的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32146518/

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