findViewById适用于TextView但不适用于兄弟Button

时间:2014-05-09 10:44:42

标签: android android-layout android-listview

我对ViewBinder的setViewValue(View,Cursor,columnIndex)有一个非常奇怪的问题。在setViewValue中,我试图访问列表视图中每个项目的布局中的按钮。

我能够访问和更改TextView的文本,但是当我尝试设置按钮的文本时,我得到一个NullPointerException。该按钮有一个id,我正确使用该名称,该按钮也是textview的兄弟,所以如果根视图可以找到textview,它应该能够找到该按钮。

我尝试清理项目但没有成功。

还有其他建议吗?

编辑: 以下是ViewBinder(setViewValue)的代码以及listview中每个项目的布局:

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>

1 个答案:

答案 0 :(得分: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;
}