我有一个非常奇怪的问题,我用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>
以布局的结构考虑,你有没有尝试使用视图层次去了'按钮'?我的意思是使用'getParent()'和'getchildAt()'方法从'TextView'开始并进入'Button'。 – Luksprog
setViewValue中的View参数是视图的根布局。也就是说,它是包含按钮和textview的LinearLayout。所以调用view.findViewById(R.id.button)应该就够了。 getChildAt()仅用于列表项目,是否正确? – Pacemaker
你能否告诉我你的代码,以便我可以指出错误。因为它通常不会发生。初始化Button时,你犯了一些小错误。 – Rizwan