java – ListView where each item is an ImageView with a radiobox and one item can be selected at a time? – Education Career Blog

I’m tearing my hair out over this. I would like a ListView where each item in the list is an ImageView. I want each item to have a radio button next to it and only one item can be selected at a time (i.e. single choice mode). This code works fine for creating a list of text box with radio buttons:

    ListView listView = ...
    String  value = {"test1","test2"};
    listView.setAdapter(
        new ArrayAdapter<String>(
            this, android.R.layout.simple_list_item_single_choice,value
    ));
    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

For my ImageView items, I implemented by own ArrayAdapter. In the getView method of my ArrayAdapter object, I load the follow xml file for each list row:

e.g.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:focusable="false"
  android:gravity="center"
>

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@android:id/text1"
  android:layout_width="fill_parent"
  android:layout_height="?android:attr/listPreferredItemHeight"
  android:textAppearance="?android:attr/textAppearanceLarge"
  android:gravity="center_vertical"
  android:checkMark="?android:attr/listChoiceIndicatorSingle"
  android:paddingLeft="6dip"
  android:paddingRight="6dip"
  /> 

  <ImageView android:id="@+id/preview"
  android:layout_width="75dip" android:layout_height="100dip"
  android:scaleType="fitCenter"
  android:enabled="true"
  android:focusable="false"
  /> 
  </RelativeLayout>

I copied the CheckedTextView item from the simple_list_item_single_choice.xml file used in the previous example. I assume that ListView must look for an item with id “text1” to use for displaying the selection status (I’m just guessing here as I cannot work out where the radio buttons are meant to come from). If I don’t include the CheckedTextView item, I don’t see any radio buttons at all.

When I use my custom adapter with the above xml file, I can see the radio buttons but selecting them does nothing. In addition, I’ve implemented the selection listener for the list view and this do not fire when I click items. What am I doing wrong?

Leave a Comment