8

アプリケーションのリストに次のように単純なカーソルアダプタを設定しています。

private static final String fields[] = {"GenreLabel", "Colour", BaseColumns._ID};


datasource = new SimpleCursorAdapter(this, R.layout.row, data, fields, new int[]{R.id.genreBox, R.id.colourBox});

R.layout.rowは、2つのTextView(genreBoxとcolourBox)で構成されています。TextViewのコンテンツを「色」の値に設定するのではなく、背景色をその値に設定したいと思います。

これを達成するために私は何をする必要がありますか?

4

2 に答える 2

13

SimpleCursorAdapter.ViewBinderをチェックしてください。

setViewValueは基本的にCursor、ビューの背景色の設定など、のデータを使って好きなことを行うチャンスです。

たとえば、次のようになります。

SimpleCursorAdapter.ViewBinder binder = new SimpleCursorAdapter.ViewBinder() {
    @Override
    public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
        String name = cursor.getColumnName(columnIndex);
        if ("Colour".equals(name)) {
            int color = cursor.getInt(columnIndex);
            view.setBackgroundColor(color);
            return true;
        }
        return false;
    }
}
datasource.setViewBinder(binder);

更新-カスタムアダプタ(拡張CursorAdaptor)を使用している場合、コードはそれほど変更されません。あなたはオーバーライドするでしょうgetViewそしてbindView

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView != null) {
        return convertView;
    }
    /* context is the outer activity or a context saved in the constructor */
    return LayoutInflater.from(context).inflate(R.id.my_row);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
    int color = cursor.getInt(cursor.getColumnIndex("Colour"));
    view.setBackgroundColor(color);
    String label = cursor.getString(cursor.getColumnIndex("GenreLabel"));
    TextView text = (TextView) findViewById(R.id.genre_label);
    text.setText(label);
}

あなたはもう少し手動でやっていますが、それは多かれ少なかれ同じ考えです。これらのすべての例で、文字列を介して列インデックスを検索する代わりに、列インデックスをキャッシュすることでパフォーマンスを節約できることに注意してください。

于 2011-04-06T22:12:39.920 に答える
0

探しているものには、カスタム カーソル アダプターが必要です。SimpleCursorAdapterをサブクラス化できます。これにより、基本的に、作成されたビューにアクセスできます (ただし、自分で作成します)。

完全な例については、カスタム CursorAdapters に関するこのブログ投稿を参照してください。特に、オーバーライドする必要があると思いますbindView

于 2011-04-06T22:17:34.263 に答える