SimpleCursorAdapter с ImageView и TextView

у вас может быть макет с imageview и textview для строки в SimpleCursorAdapter со списком?

это будет макет

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<ImageView
    android:id="@+id/icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/bowler_txt"
    android:paddingLeft="25dp"
    android:textSize="30dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Bowler"
    android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

можно ли это сделать в SimpleCursorAdapter со списком? когда мне нужны были изображения в списке, я всегда использовал собственный адаптер массива, но никогда не использовал курсор.

Как бы я установил изображение, если это можно сделать?


person tyczj    schedule 14.12.2011    source источник


Ответы (2)


Когда представление для привязки является ImageView и нет существующих ViewBinder связанных SimpleCursorAdapter.bindView() вызовов setViewImage(ImageView, String). По умолчанию значение будет рассматриваться как ресурс изображения. Если значение нельзя использовать в качестве ресурса изображения, оно используется как Uri изображения.

Если вам нужно отфильтровать другими способами значение, полученное из базы данных, вам нужно добавить ViewBinder к ListAdapter следующим образом:

listAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder(){
   /** Binds the Cursor column defined by the specified index to the specified view */
   public boolean setViewValue(View view, Cursor cursor, int columnIndex){
       if(view.getId() == R.id.your_image_view_id){
           //...
           ((ImageView)view).setImageDrawable(...);
           return true; //true because the data was bound to the view
       }
       return false;
   }
});
person Francesco Vadicamo    schedule 14.12.2011

Чтобы расширить ответ @Francesco Vadicamo, это функция, которая является частью более крупной деятельности. Я разделил его, потому что мне нужно было вызывать его из нескольких областей кода. databaseHandler и listView определяются как переменные класса и инициализируются в onCreat().

private void updateListView() {
    // Get a Cursor with the current contents of the database.
    final Cursor cursor = databaseHandler.getCursor();

    // The last argument is 0 because no special behavior is required.
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
            R.layout.listview,
            cursor,
            new String[] { databaseHandler.ICON, databaseHandler.BOWLER_TXT },
            new int[] { R.id.icon, R.id.bowler_txt },
            0);

    // Override the handling of R.id.icon to load an image instead of a string.
    adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            if (view.getId() == R.id.imageview) {
                // Get the byte array from the database.
                byte[] iconByteArray = cursor.getBlob(columnIndex);

                // Convert the byte array to a Bitmap beginning at the first byte and ending at the last.
                Bitmap iconBitmap = BitmapFactory.decodeByteArray(iconByteArray, 0, iconByteArray.length);

                // Set the bitmap.
                ImageView iconImageView = (ImageView) view;
                iconImageView.setImageBitmap(iconBitmap);
                return true;
            } else {  // Process the rest of the adapter with default settings.
                return false;
            }
        }
    });

    // Update the ListView.
    listView.setAdapter(adapter);
}
person Soren Stoutner    schedule 04.07.2016