2012-07-17 60 views
0

感謝來自stackoverflow用戶的幫助,我設法根據某些條件更改某個特定行的顏色。但改變顏色並不完全符合我的需求和期望。如何設置特定的ListView行的文本/圖像 - Android?

所以我開始瀏覽網頁並試圖改變它。我想在特定行的TextView中設置文本。爲了能夠改變行顏色,我被建議創建個性化的SimpleCursorAdapter類,因爲我使用Cursor從SQLite中獲取值到ListView中。

閱讀並對其進行測試,這是我想出了之後:

public class MyCursorAdapter extends SimpleCursorAdapter { 
    public MyCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { 
     super(context, layout, c, from, to); 
    } 

    @Override 
    public void bindView(View view, Context context, Cursor cursor) { 
     super.bindView(view, context, cursor); 
     if(cursor.getLong(cursor.getColumnIndex(MyDBAdapter.KEY_PRICE)) == 5) 
     { 
      TextView price = (TextView)view.findViewById(R.id.priceInfo); 
      price.setText("High"); 
     } 
     else 
      view.setBackgroundColor(0x00000000); 
    } 
} 

然而,什麼我現在越來越被複制在某些行文字(有規律性的話)。當我在某處閱讀時,每個滾動條都會刷新ListView,但是如果我在if子句中放入(此TextView已排除)此行時可能如何:view.setBackgroundColor(SELECTED_COLOR);一切正常,只有這一行已更改。

有人可以告訴我,我必須做些什麼才能使它有效,或者我的想法有什麼錯誤?

回答

1
public class MyCursorAdapter extends SimpleCursorAdapter { 
    public MyCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { 
     super(context, layout, c, from, to); 
    } 

    @Override 
    public void bindView(View view, Context context, Cursor cursor) { 
     super.bindView(view, context, cursor);   
     TextView price = (TextView)view.findViewById(R.id.priceInfo); 
     if(cursor.getLong(cursor.getColumnIndex(MyDBAdapter.KEY_PRICE)) == 5) 
     { 
      price.setText("High"); 
      view.setBackgroundColor(/* red color? */); 
     } 
     else { 
      price.setText(""); 
      view.setBackgroundColor(0x00000000); 
     } 
    } 
} 

因爲 「itemrecycling」 在bindView的觀點具有一個被回收的顏色和文本。您需要爲每個在不同列表視圖項目上進行更改的bindView調用顯式指定所有屬性。在這種情況下,backgroundcolor和價格標籤。

0

重寫getView方法並根據listview項的位置使用convertView.setbackgroundColor。

事情是這樣的:

public class MyCustomAdapter extends ArrayAdapter<String> { 

public MyCustomAdapter(Context context, int textViewResourceId, 
String[] objects) { 
super(context, textViewResourceId, objects); 
// TODO Auto-generated constructor stub 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
// TODO Auto-generated method stub 
return super.getView(position, convertView, parent); 
if(postion == 1) //1st position in listview 
{ 
    convertView.setbackgroundColor(...) 
} 

等等...

+0

1.我不想改變背景顏色。我現在可以做到這一點,更容易。所以如果我有2 000個元素,我必須製作一個循環或什麼東西來處理這些瘋狂的事情? – sebap123 2012-07-17 13:23:46

+0

據我所知,listview(這是一個小混亂,是的),如果你想修改某些行中的元素,最好的方法是通過比較列表中的位置。 – pixelscreen 2012-07-17 13:34:20

+0

所以,你不知道好。我在我的問題中發佈的方法在我們談論行顏色變化時起作用。但它不適用於文本或圖像集。如果你有光標,你不必做任何循環。 – sebap123 2012-07-17 13:45:28

相關問題