2014-05-09 38 views
1

我有一個非常奇怪的問題,我用ViewBinder的setViewValue(View,Cursor,columnIndex)。在setViewValue中,我試圖訪問我的列表視圖中每個項目的佈局按鈕。findViewById適用於TextView,但不適用於兄弟按鈕

我能夠訪問和更改TextView的文本,但是當我嘗試設置按鈕的文本時,我得到一個NullPointerException。該按鈕有一個ID,我正確使用該名稱,該按鈕也是textview的兄弟,所以如果根視圖可以找到該textview,它應該能夠找到該按鈕。

我試圖清理項目沒有成功。

其他建議?

編輯: 下面是ViewBinder(setViewValue)的代碼,並在列表視圖的佈局爲每個項目:

private class CustomViewBinder implements ViewBinder { 

    @Override 
    public boolean setViewValue(View view, Cursor cursor, int columnIndex) { 

      int upvoted_index=cursor.getColumnIndex("upvote"); 
      int is_upvoted = cursor.getInt(upvoted_index); 
      if (is_upvoted == 1) { 

       Button likeButton = (Button) view.findViewById(R.id.voteButton); 
       likeButton.setText("Upvoted"); 
       return true; 
      } 
      return false; 
    } 

} 

佈局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/container" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" 
android:paddingBottom="20dip" 
android:background="@drawable/profile_styling" > 

    <TextView 
    android:id="@+id/title" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:textSize="30sp" 
    android:gravity="center" /> 


<Button 
android:id="@+id/voteButton" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:gravity="center" 
android:text="@string/like" 
android:background="#00FFFF" 
android:paddingTop="20dp" 
/> 

</LinearLayout> 
+0

以佈局的結構考慮,你有沒有嘗試使用視圖層次去了'按鈕'?我的意思是使用'getParent()'和'getchildAt()'方法從'TextView'開始並進入'Button'。 – Luksprog

+0

setViewValue中的View參數是視圖的根佈局。也就是說,它是包含按鈕和textview的LinearLayout。所以調用view.findViewById(R.id.button)應該就夠了。 getChildAt()僅用於列表項目,是否正確? – Pacemaker

+0

你能否告訴我你的代碼,以便我可以指出錯誤。因爲它通常不會發生。初始化Button時,你犯了一些小錯誤。 – Rizwan

回答

3

您可以使用:

ViewGroup superView = (ViewGroup)view.getParent(); 
Button btn = (Button) superView.findViewById(R.id.votewButton); 

還使用您傳遞給適配器的視圖ID數組'構造器將是一個很好的選擇:

String[] from = {/*any collumns that you may have*/, "_id"}; // just bind a column, we don't use it 
int[] = {/*any collumns that you may have*/, R.id.voteButton}; 

ViewBinder你必須:

@Override 
public boolean setViewValue(View view, Cursor cursor, int columnIndex) { 
    // only if we're binding the Button 
    if (view.getId == R.id.voteButton) { 
     int upvoted_index=cursor.getColumnIndex("upvote"); 
     int is_upvoted = cursor.getInt(upvoted_index); 
     if (is_upvoted == 1) { 
      Button likeButton = (Button) view; 
      likeButton.setText("Upvoted"); 
      return true; 
     } 
    } 
    return false; 
} 
+0

getParent()返回ViewParent而不是查看 – Somil

+0

@Superbiji這是怎麼回事?你有完全相同的場景嗎?你究竟想要做什麼? – Luksprog

相關問題