我有:
MyListActivity class extends ListActivity
setContentView(R.layout.mylist)
; mylist.xml
和list_row.xml
。 mylist.xml
是布局,list_row.xml
是每行的样子。 list_row.xml
包含3 TextViews(t1,t2,t3)
。 我想在MyListActivity
类中更改某些t2文本。因为内容视图是mylist.xml所以我不能简单地使用findViewById
。所以我使用了LayoutInflater
。
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.list_row, null);
textView2 = (TextView) v.findViewById(R.id.t2);
textView2.setText("ccccc");
问题是t2的文本永远不会改变。我已经尝试了很多次,文本仍然是我在list_row.xml
中设置的文本。我无法弄清楚为什么......请有人帮忙。谢谢!
=====的解决方案:=====
创建我自己的SimpleCursorAdapter
类并覆盖getView()
方法。
private class MySimpleCursorAdapter extends SimpleCursorAdapter {
Cursor c;
public MySimpleCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
this.c = c;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
super.getView(position, convertView, parent);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_row, parent, false);
TextView textview1 = (TextView) rowView.findViewById(R.id.text1);
textView1.setText(c.getString(1));// whatever should be in textView1
textView2 = (TextView) rowView.findViewById(R.id.text2);
textView2.setText("ccccc");
return rowView;
}
}
super.getView(position, convertView, parent);
非常重要,因为如果我没有该行,textView1
将始终显示第一行的值(例如,如果textView1
显示该ID,那么这是总是1)。
答案 0 :(得分:1)
如果您想更改TextView
文字,则必须在ListView
的适配器中进行更改。
答案 1 :(得分:0)
更改文字视图的最佳方法是getView()
。请参阅this示例以获取更多信息。