【问题标题】:How to set background color through SimpleCursorAdapter如何通过 SimpleCursorAdapter 设置背景颜色
【发布时间】:2015-06-12 01:15:52
【问题描述】:

这是我的代码:

private void fillData() {
        Cursor notesCursor = mDbHelper.fetchAllNotes();
        startManagingCursor(notesCursor);

        String[] from = new String[]{NotesDbAdapter.KEY_TITLE, NotesDbAdapter.KEY_COLOR};

        int[] to = new int[]{R.id.text1, R.id.text2};

        SimpleCursorAdapter notes = new SimpleCursorAdapter(
              this, R.layout.note_row, notesCursor, from, to);
        setListAdapter(notes);
        }

这会产生以下 ListView:http://i.stack.imgur.com/7W1xa.jpg

我想要的是获取“R.id.text2”值(这是一种十六进制颜色)并将其设置为自身的文本颜色,用于我的 ListView 的每个不同行。

结果应如下所示:http://i.stack.imgur.com/wrXt8.jpg

这可能吗?谢谢。

【问题讨论】:

    标签: android listview simplecursoradapter


    【解决方案1】:

    是的,这是可能的。创建您自己的光标适配器 MyCursorAdapter 扩展 SimpleCursorAdapter,然后覆盖 newViewbindView 方法。

    public class MyCursorAdapter extends SimpleCursorAdapter {
    public MyCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
        super(context, layout, c, from, to);
    }
    
    public MyCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
        super(context, layout, c, from, to, flags);
    }
    
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        super.bindView(view, context, cursor);
        TextView textView = (TextView) view.findViewById(R.id.text2);
        String color = cursor.getString(cursor.getColumnIndex(NotesDbAdapter.KEY_COLOR));
        textView.setBackgroundColor(Color.parseColor(color));
    }
    
    }
    

    【讨论】:

      【解决方案2】:

      无需创建新类。请参阅此代码。

      @Override
      public boolean setViewValue(View view, Cursor c, int columnIndex) {
          if(columnIndex == c.getColumnIndexOrThrow(NotesDbAdapter.KEY_COLOR)) {
              TextView tv = (TextView)view;
              tv.setColor(Color.RED);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-02-08
        • 2012-07-18
        • 1970-01-01
        • 2010-12-11
        • 2014-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-06
        相关资源
        最近更新 更多