Java 如何在listView的自定义行视图中设置textView
我试图在listView的自定义行视图中设置textView,如下所示,但应用程序在返回空指针异常时崩溃Java 如何在listView的自定义行视图中设置textView,java,android,Java,Android,我试图在listView的自定义行视图中设置textView,如下所示,但应用程序在返回空指针异常时崩溃 TextView txtrow = (TextView) getListView().getChildAt(i).findViewById(R.id.text11); txtrow.setText("text"); 但当我把它放在setOnClickListener下时,它就工作了 button.setOnClickListener(new View.OnClickListener() {
TextView txtrow = (TextView) getListView().getChildAt(i).findViewById(R.id.text11);
txtrow.setText("text");
但当我把它放在setOnClickListener下时,它就工作了
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView txtrow = (TextView) getListView().getChildAt(i).findViewById(R.id.text11);
txtrow.setText("text");
}
});
您应该在ListView的适配器中执行此操作。无论您使用的是什么数据,适配器都应该包含所需的文本,以便在
getView()
中实际创建行视图时,可以在适当的TextView上设置它
需要注意的是,getChildAt(index)
从列表视图的当前子级返回给定索引处的子级。换句话说,getChildAt(0)
不一定在位置0处提供列表项。用户可能已滚动列表,以便它现在显示从位置10到15(例如)的数据,在这种情况下,getChildAt(0)
为您提供位置10的视图,而不是位置0。getChildAt(i),i是listView的项目位置。
To set text in custom row in listview
Please follow the following points
1. custom arrayadapter by extending Arrayadpater (for simple)
2. and overwrite getview as following
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
textView.setText(values[position]);
return rowView;
}
3. and set the adapter to the listview
And for more detial please refer this site
[http://www.vogella.com/tutorials/AndroidListView/article.html][1]