我如何获得listview的孩子?

时间:2017-11-09 02:26:29

标签: android listview nullpointerexception

我想在单击

的列表视图中更改textview中的文本
listViewMessage = (ListView) rootview.findViewById(R.id.listView);      
listViewMessage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
     public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
     txtViewMess = (TextView) listViewMessage.getChildAt(position).findViewById(R.id.textViewMessage); //error
     txtViewMess.setText("Paid");
    }
    });

代码适用于几个textview,但有些转向

 java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference

3 个答案:

答案 0 :(得分:1)

就这样得到它

TextView tv=adapterView.getSelectedView().findViewById(R.id.my_tv);

答案 1 :(得分:1)

您使用错误的视图初始化文本视图:

listViewMessage = (ListView) rootview.findViewById(R.id.listView);      
listViewMessage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, final int 
position, long id) {
txtViewMess = (TextView) 
view.getChildAt(position).findViewById(R.id.textViewMessage); //error
txtViewMess.setText("Paid");
}
});

答案 2 :(得分:0)

您可以在代码中使用c:/path/scrapy.exe scrapy startproject tutorial

<强> YourAdapter

callback

通话方法

@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
    ViewHolder viewHolder = null;
    ...
    viewHolder.mTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mTextClickListener.onTextClick(i);
        }
    });
    return view;
}

/**
 * text click
 */
public interface onItemTextClickListener {
    void onTextClick(int i);
}

private onItemTextClickListener mTextClickListener;

public void setOnItemTextClickListener(onItemTextClickListener mTextClickListener) {
    this.mTextClickListener = mTextClickListener;
}

class ViewHolder {
    TextView mTextView;
}