2011-04-22 25 views
1

我有一個使用SimpleCursorAdapter從SQLite數據庫填充的列表視圖。其中一個在遊標中返回的列是一個整數值0或1.在我的列表視圖中,我想以更友好的形式(即「Yes」或「No」)顯示它,並可能使用不同的文本顏色爲每個。下面是我的源:Android應用程序,ListView中的條件文本

Cursor c = dbHelper.fetchAllItems(); 
startManagingCursor(c); 

String[] from = {"deployed", "designation", "serial"}; 
int[] to = {R.id.deployed, R.id.designation, R.id.serial}; 

setListAdapter(new SimpleCursorAdapter(this, R.layout.list_item, c, from, to)); 

我將如何有條件開關元件和/或屬性的佈局時,SimpleCursorAdapter每個視圖的列名映射簡單。 (它是安全的假設,我不能使用SimpleCursorAdapter做到這一點?)

+1

可能不應該使用simplecursoradapter。像這樣使用simplecursoradapter並不意味着需要進行很多定製 – binnyb 2011-04-22 19:16:52

回答

3

通過添加自定義適配器,擴展的CursorAdapter

解決

修改:

Cursor c = dbHelper.fetchAllItems(); 
startManagingCursor(c); 

setListAdapter(new RowAdapter(this, c)); 

新嵌套類:

private static class RowAdapter extends CursorAdapter { 

    public RowAdapter(Context context, Cursor c) { 
     super(context, c); 
    } 

    public void bindView(View view, Context context, Cursor c) { 
     TextView vDesignation = (TextView) view.findViewById(R.id.designation); 
     TextView vSerial = (TextView) view.findViewById(R.id.serial); 
     TextView vDeployed = (TextView) view.findViewById(R.id.deployed); 

     String designation = c.getString(c.getColumnIndexOrThrow("designation")); 
     String serial = c.getString(c.getColumnIndexOrThrow("serial")); 
     int deployed = c.getInt(c.getColumnIndexOrThrow("deployed")); 

     vDesignation.setText(designation); 
     vSerial.setText(serial); 
     vDeployed.setText(deployed > 0 ? R.string.yes : R.string.no); 
     vDeployed.setTextColor(deployed > 0 ? view.getResources().getColor(R.color.yes) : view.getResources().getColor(R.color.no)); 
    } 

    public View newView(Context context, Cursor c, ViewGroup parent) { 
     LayoutInflater inflater = LayoutInflater.from(context); 
     View view = inflater.inflate(R.layout.list_item, parent, false); 
     bindView(view, context, c); 
     return view; 
    } 
} 
相關問題