我对Android应用程序有点问题。我正在尝试创建一个listview,每行包含一个textview和一个checkedtextview。我已经完成了布局和适配器,它正确地显示了所有的项目,但我遇到的问题是:我可以完美地检查前7项(最初可见的项),但当我向下滚动检查以下项中的一项(最初不可见的项)时,我得到一个空指针异常。我该怎么办?
适配器代码:
private class myAdapter extends ArrayAdapter<Orders> {
private ArrayList<Orders> items;
public myAdapter(Context context, int resource, ArrayList<Orders> items) {
super(context, resource, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.orderslist_row,
null);
}
Orders o = items.get(position);
CheckedTextView txtSymbol = (CheckedTextView) convertView
.findViewById(R.id.checkedTextView1);
txtSymbol.setText(o.getInstrumentID());
CheckedTextView txtQuantity = (CheckedTextView) convertView
.findViewById(R.id.checkedTextView2);
Double qty = o.getQuantity();
txtQuantity.setText(FormatNumber.Number(qty, 0));
if (o.getStatus().toString().equals("Rejected"))
txtQuantity.setTextColor(Color.RED);
if (o.getStatus().toString().equals("Active"))
txtQuantity.setTextColor(Color.GREEN);
return convertView;
}}
和OnItemClickCode:
public void onItemClick(AdapterView<?> adapter, View view, int position,
long id) {
View v = (View)lstOrders.getChildAt(position);
CheckedTextView ctv = (CheckedTextView) v.findViewById(R.id.checkedTextView2);
ctv.toggle();}
发布于 2012-12-11 20:56:18
getChildAt(i)在一组可见的索引上工作。当滚动到位置3成为第一个可见行时,它就变成了该方法的位置0。因此,在任何给定的时刻,如果屏幕上可以容纳列表视图行的数量,那么您最多只能使用索引7。如果你继续使用这个方法,有一种方法可以用你想要的方式来衡量,你可以找到第一个可见的行索引是什么,然后从总数中减去。listview就有这样一个方法。
public void onItemClick(AdapterView<?> adapter, View view, int position,
long id) {
View v = (View)lstOrders.getChildAt(position - lstOrders.getFirstVisiblePosition());
CheckedTextView ctv = (CheckedTextView) v.findViewById(R.id.checkedTextView2);
ctv.toggle();
}https://stackoverflow.com/questions/13819176
复制相似问题