2012-12-11 52 views
1

我有一個Android應用程序的問題。我試圖創建一個包含textview和每行checkedtextview的列表視圖。我已經完成了佈局和適配器,它正確顯示了所有項目,但是我遇到的問題是以下幾點:我可以完美地檢查前7項(最初可見的項目),但是當我向下滾動以檢查其中一項下面的項目(不可見初始化)我得到一個空指針異常。我該怎麼辦?Android系統視圖checkedtextview

適配器代碼:

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

getChildAt(i)作品落定是可見的指標的。當您滾動並且位置3成爲第一個可見行時,該位置已成爲方法的位置0。因此,在任何特定時刻,只允許最多索引7,如果這是多少個listview行可以放在屏幕上。如果您繼續使用這種方法,您可以通過一種方式提高刻度,您會發現第一個可見行索引是什麼,然後從總量中減去。 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(); 
} 
+0

ty芒果,它的工作原理,但我怎麼能通過整個列表視圖(例如for循環),並獲得訪問列表中的所有checkedtextviews? –

+0

你想在什麼條件下做到這一點?你想讓他們都統一做點什麼嗎?我不認爲繼續'getChildAt'會是最好的。更好的辦法是在你的適配器中有一個你可以修改的集合。然後根據集合在相應位置讀取的內容,在'getView'中使用if語句。 – mango

+0

我想對檢查的項目執行一些操作,例如刪除它們。 –