【问题标题】:SimpleCursorAdapter.ViewBinder - Apply differently to each row (ListFragment)SimpleCursorAdapter.ViewBinder - 以不同方式应用于每一行 (ListFragment)
【发布时间】:2013-06-04 17:45:59
【问题描述】:

在我的应用程序中,我从 SQlite 数据库中提取 3 个字符串来填充 ListView。在列表行中,我必须使用 TextViews 和 ImageView。

两个 TextView 当前已正确填充(每行中的文本不同)。但是,我使用 ViewBinder 设置的 ImageView 并非如此。即,每一行中的图像都得到相同的颜色。我怎样才能解决这个问题?我需要扩展 SimpleCursorAdapter 吗?

String[] from = {DbHelper.NAME, DbHelper.COMMENT, DbHelper.COLOR};
String[] column = {DbHelper.C_ID, DbHelper.NAME, DbHelper.COMMENT, DbHelper.COLOR};
int[] to = {R.id.listitem_title, R.id.listitem_summary, R.id.listitem_color};

Cursor cursor = db.query(DbHelper.TABLE_NAME, column, null, null, null, null, null);

this.adapter = new SimpleCursorAdapter(getActivity(), R.layout.list_item_set, cursor, from, to);

adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
    if (view.getId() == R.id.listitem_color) {

        cursor.moveToFirst();
        String color = "#ffffff";
        while (cursor.moveToNext()) {
        color = cursor.getString(cursor.getColumnIndex(DbHelper.COLOR));
        }
        ((ImageView) view).setBackgroundColor(Color.parseColor(color));
            return true;
        }
        return false;
         }
    });

setListAdapter(adapter);

【问题讨论】:

    标签: java android simplecursoradapter android-listfragment


    【解决方案1】:

    即每一行的图像都得到相同的颜色。我该如何解决 这个?

    如果你要使用:

    String color = "#ffffff";
    while (cursor.moveToNext()) {
        color = cursor.getString(cursor.getColumnIndex(DbHelper.COLOR));
    }
    

    这将使color 指向出现在Cursor 最后一行的颜色,因为您循环遍历整个Cursor。相反,您只需从Cursor 获取color

    String color = "#ffffff";
    color = cursor.getString(cursor.getColumnIndex(DbHelper.COLOR));
    

    【讨论】:

    • 非常好(也不得不删除 cursor.moveToFirst)谢谢伙计!
    • @Jakob 是的,Cursor 已经定位指向正确的行,您只需要从中检索数据。
    猜你喜欢
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多