【发布时间】:2013-07-29 09:02:22
【问题描述】:
我有一个带有一些复选框的列表视图,我需要根据存储在数组中的一些数据自动检查它们。我的扩展基本适配器的自定义适配器:
public class MyAdapter extends BaseAdapter
{
private Context context;
public SPCMjereAdapter(Context c)
{
context = c;
}
public int getCount() {
return MyArrList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public int getlistItemsCount()
{
return listView.getChildCount();
}
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_list_row, null);
}
// ColID
TextView txtOpis = (TextView) convertView.findViewById(R.id.ColOpis);
txtOpis.setText(MyArrList.get(position).get("OpisMjere") +".");
// ColCode
TextView txtRbMjere = (TextView) convertView.findViewById(R.id.ColCode);
txtRbMjere.setText(MyArrList.get(position).get("RbMjere"));
// ColChk
CheckBox Chk = (CheckBox) convertView.findViewById(R.id.ColChk);
Chk.setTag(MyArrList.get(position).get("RbMjere"));
return convertView;
}
}
这就是我检查项目的方式
int k=0;
int j=0;
for (j=0; j<numberOfItems; j++)
{
LinearLayout itemLayout = (LinearLayout)listView.getChildAt(j); // Find by under LinearLayout
CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.ColChk);
for (k=0; k<rbmjere.size(); k++)
{
if (checkbox.getTag().toString() == rbmjere.get(k).toString())
{
checkbox.setChecked(true);
}
}
}
问题出在一行
LinearLayout itemLayout = (LinearLayout)listView.getChildAt(j);
因此,如果我调用此代码来检查项目,问题是 listview 显示例如 3 个项目,但代码仅识别 2 个项目并且缺少第三个项目。如何检测所有项目何时可见或如何检测列表视图何时渲染完成?
【问题讨论】:
-
我建议你在for循环中使用
int count = listView.getChildCount();然后for (j=0; j<count; j++)。 -
看看你的
for循环 - 它只循环两次 - 对于 0 和 1(它是 -
但是该放在哪里呢?我想在 listview 加载所有数据后检查项目。我不确定我的逻辑是否正确......
-
问题是把那个循环放在哪里?在 getView() 内部还是其他地方?
-
您无需转换为 LinearLayout 即可使用 findViewById。您无需强制转换为 Checkbox 即可使用 setTag。 numberOfItems 应该作为 listView.getChildCount 获得,它返回在 ListView 中可见的项目(不要与“所有项目都在那里以适配器.getCount 的长度创建”混淆)这是什么 - checkbox.getTag().toString() == rbmjere.get(k).toString() ?字符串不能像这样比较。如果要比较对象实例,则不必将它们转换为字符串。如果你想比较 String 的值,你应该使用 Strings 的 Object.equals() 方法。
标签: android android-listview nullpointerexception