Android app, conditional text in ListView

感情迁移 提交于 2019-12-08 04:55:55

问题


I have a list view that is being populated from an SQLite database using the SimpleCursorAdapter. One of the columns being returned in the cursor is an integer value 0 or 1. In my list view, I would like to display this in a more friendly form (ie. "Yes" or "No") and possibly with different text colors for each. Here is my source:

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));

How would I conditionally switch elements and/or properties in the layout when the SimpleCursorAdapter simply maps each view to a column name. (Is it safe to assume I can't use SimpleCursorAdapter to accomplish this?)


回答1:


Solved by adding a custom adapter, extending CursorAdapter

Modification:

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

setListAdapter(new RowAdapter(this, c));

New nested class:

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;
    }
}


来源:https://stackoverflow.com/questions/5759101/android-app-conditional-text-in-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!