2011-03-03 90 views
7

我想做一個非常簡單的事情。我在我的應用程序中有一個列表視圖,我動態添加文本。但是,在某一點之後,我想改變列表視圖中文本的顏色。所以,我做了一個定義我的自定義列表項的XML,並對ArrayAdapter進行了子類化。但是,無論何時在我的自定義ArrayAdapter上調用add()方法,項目都會添加到列表視圖中,但文本不會放入它。覆蓋Android ArrayAdapter

這裏是我的XML:`

<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/list_content" android:textSize="8pt" 
    android:gravity="center" android:layout_margin="4dip" 
    android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#FF00FF00"/> 

而且我ArrayAdapter子類:

private class customAdapter extends ArrayAdapter<String> { 
    public View v; 
    public customAdapter(Context context){ 
     super(context, R.layout.gamelistitem); 
    } 

    @Override 
    public View getView(int pos, View convertView, ViewGroup parent){ 
     this.v = convertView; 
     if(v==null) { 
      LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      v=vi.inflate(R.layout.gamelistitem, null); 
     } 

     if(timeLeft!=0) { 
      TextView tv = (TextView)v.findViewById(R.id.list_content); 
      //tv.setText(str[pos]); 
      tv.setTextColor(Color.GREEN); 
     } 
     else { 
      TextView tv = (TextView)v.findViewById(R.id.list_content); 
      //tv.setText(str[pos]); 
      tv.setTextColor(Color.RED); 
     } 

     return v; 
    } 
} 

我知道我在做什麼可怕的錯誤,但我還是有點新到Android 。

謝謝! `

回答

10

您需要設置getView()中的文字。獲取設置值getItem(pos),然後進行設置。

public View getView(int pos, View convertView, ViewGroup parent){ 
    this.v = convertView; 
    if(v==null) { 
     LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     v=vi.inflate(R.layout.gamelistitem, null); 
    } 

    // Moved this outside the if blocks, because we need it regardless 
    // of the value of timeLeft. 
    TextView tv = (TextView)v.findViewById(R.id.list_content); 
    tv.setText(getItem(pos)); 

    if(timeLeft!=0) { 
     //TextView tv = (TextView)v.findViewById(R.id.list_content); 
     //tv.setText(str[pos]); 
     tv.setTextColor(Color.GREEN); 
    } 
    else { 
     //TextView tv = (TextView)v.findViewById(R.id.list_content); 
     //tv.setText(str[pos]); 
     tv.setTextColor(Color.RED); 
    } 

    return v; 
} 

此外,有沒有你存儲v作爲成員變量,而不是僅僅在函數內部的一個原因?

+0

我正在存儲v因爲我想我可能需要重寫add()方法,因爲我的ListView以無內置入口開始,但它隨着時間的推移而獲得對象。 – 2011-03-03 06:04:35

+0

@ Brian515:啊。這是擴展像ArrayAdapter這樣的全功能類的好方法之一。它已經處理了幾乎所有你需要的東西(比如'add()'),你可以擔心像自定義數據或自定義視圖這樣的奇數位。 – erichamion 2011-03-03 06:17:26

+0

我還沒有機會玩過ListView(我剛開始),但從我對你正在做什麼以及ListView如何工作的理解中,我可以看到另一個潛在的問題。據我所知,ListView可以回收視圖,因此如果您在添加視圖時檢查timeLeft的值,那麼隨着用戶上下滾動,舊項目可能會從綠色變爲紅色。如果發生這種情況,可能考慮使用一個對象,該對象在創建時包含String和當前timeLeft,而不僅僅是String? – erichamion 2011-03-03 06:23:06