我有:的setText()的TextView在list_row.xml
- 一個
MyListActivity class extends ListActivity
setContentView(R.layout.mylist)
; - 兩個xml文件:
mylist.xml
和list_row.xml
。 mylist.xml
是佈局,list_row.xml
是每行的樣子。list_row.xml
包含3TextViews(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)。
嗨,感謝您的回覆。我有一個SimpleCursorAdaper,我已經'公開查看newView(上下文上下文,遊標光標,ViewGroup父)'哪些「膨脹視圖從指定的XML文件」和「公共抽象視圖getView(int位置,查看convertView,ViewGroup父母)',我可以從XML文件充氣。但在API中,它沒有說如何膨脹。你能提供一個例子的鏈接嗎?非常感謝 – Dongminator 2012-02-21 10:22:09
另一個問題。根視圖是列表視圖,每行都是列表視圖的子項? – Dongminator 2012-02-21 10:33:11
是的,問題解決了!剛剛添加了'MySimpleCursorAdapter'並重寫'getView()'並在那裏改變文本。事實證明'getView()'由適配器爲每一行調用。謝謝! – Dongminator 2012-02-21 10:47:05