2012-05-06 31 views
0

監聽器代碼:NullPointerException異常而訪問ListView的項目值

lvSearch.setOnItemClickListener(new OnItemClickListener() { 

     public void onItemClick(AdapterView<?> adapter, View view, int position, 
       long id) { 
      LinearLayout ll = (LinearLayout) adapter.getChildAt(position); 
      TextView tx = (TextView) ll.getChildAt(0); 
      TextView tx1 = (TextView) ll.getChildAt(1); 
      Log.i("abcValues", tx.getText().toString()); 

我得到一個NullPointerException在訪問ListView的項目值。對於啓動項目值而言,它工作正常,但對於滾動後出現的項目不起作用。

+0

您是否使用適配器來填充您的列表視圖?如果是這樣,你應該嘗試從那裏處理點擊,在你從getView()方法返回它之前設置你的ClickListener。每次點擊一個項目時調用findViewById()會導致性能稍差。另外更改「argo0」等更具描述性。然後添加日誌語句,它會告訴你什麼值傳遞給你的onItemClick() – FoamyGuy

+1

請把整個代碼.. –

回答

1

getChildAt返回可見行,當你滾動LisView,然後單擊行,你會打電話給無效位置的方法getChildAt(您可以用getChildAt方法使用的最大數量是可見的行數 - 1)。如果你想從點擊的行佈局的父,只需用第二個參數arg1在你的代碼:

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
       long arg3) { 
     LinearLayout ll = (LinearLayout) arg1; 
     TextView tx = (TextView) ll.getChildAt(0); 
     TextView tx1 = (TextView) ll.getChildAt(1); 
     Log.i("abcValues", tx.getText().toString()); 
+0

但我怎麼能從arg1(視圖)獲取子值? plz幫助.. – kamil

+0

@kamil在你指的是什麼'得到孩子價值'? 'arg1'是你點擊的行的'View'。然後你可以像上面的代碼那樣用'll.getChildAt'訪問孩子'TextView',或者你可以通過id:'ll.findViewById(R.id.textview_id);'來找到它。然後你可以像你想要的那樣使用它。 – Luksprog

+0

達尼特,當我開始我的答案並且不得不接電話時打我。 +1 – Barak

0

我不認爲你可以這樣做的。嘗試從傳遞的視圖中返回:

LinearLayout row = (LinearLayout) arg1.getParent(); 
    TextView tx = (TextView) row.findViewById(R.id.tx_id_here); 
    TextView tx1 = (TextView) row.findViewById(R.id.tx1_id_here); 
+0

你不能在'arg1'上調用'getParent()',因爲當你嘗試將'ListView'(如果我沒記錯的話)投射到一個'LinearLayout'時,它會拋出一個異常。 – Luksprog

+0

我如何在單獨的按鈕上訪問我的列表視圖項目而不是項目單擊偵聽器。 – kamil

+0

@kamil你不這樣做,這是沒有意義的。當你在佈局中點擊一個'Button'時,你會引用哪個列表項(我認爲'Button'不在列表行佈局中)?你應該問另一個問題。 – Luksprog

相關問題