2012-02-18 62 views
0

我有:的setText()的TextView在list_row.xml

  1. 一個MyListActivity class extends ListActivitysetContentView(R.layout.mylist);
  2. 兩個xml文件:mylist.xmllist_row.xml
  3. mylist.xml是佈局,list_row.xml是每行的樣子。
  4. 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)。

回答

1

如果您想更改TextView文本,您必須在ListView的適配器中執行此操作。

+0

嗨,感謝您的回覆。我有一個SimpleCursorAdaper,我已經'公開查看newView(上下文上下文,遊標光標,ViewGroup父)'哪些「膨脹視圖從指定的XML文件」和「公共抽象視圖getView(int位置,查看convertView,ViewGroup父母)',我可以從XML文件充氣。但在API中,它沒有說如何膨脹。你能提供一個例子的鏈接嗎?非常感謝 – Dongminator 2012-02-21 10:22:09

+0

另一個問題。根視圖是列表視圖,每行都是列表視圖的子項? – Dongminator 2012-02-21 10:33:11

+0

是的,問題解決了!剛剛添加了'MySimpleCursorAdapter'並重寫'getView()'並在那裏改變文本。事實證明'getView()'由適配器爲每一行調用。謝謝! – Dongminator 2012-02-21 10:47:05

0

最好的方法來改變你的textview是在getView()。請參閱this示例以獲取更多信息。