Android listview checkedtextview

时间:2012-12-11 11:14:51

标签: android android-listview checkedtextview

我的Android应用有问题。我正在尝试创建一个包含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();

}

1 个答案:

答案 0 :(得分:1)

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();
}