How to enable radio button in android listview?

62 Views Asked by At

I want to enable radio button in android listview. I don't want to use any custom adapter to display radio button.

Here is my code:

private String[] items = {"Item 1", "Item 2", "Item 3", "Item 4"};
View contentsView = inflater.inflate(R.layout.trusted_credential_list_container, parent, false);

ListView mList = (ListView) contentsView.findViewById(R.id.cert_list);
mList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
        android.R.layout.simple_list_item_1, items);
mList.setAdapter(adapter);

In xml,

<ListView
    android:id="@+id/cert_list"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:choiceMode="singleChoice">
</ListView>

Eventhough I used choiceMode as singleChoice, why radio button is not displaying?

Second type I used without radio button in custom adapter that has only textview:

ListView mList = (ListView) contentsView.findViewById(R.id.cert_list);
mList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

/*ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
        android.R.layout.simple_list_item_checked, items);
mList.setAdapter(adapter);*/

ArrayList<User> arrayOfUsers = User.getUsers();
// Create the adapter to convert the array to views
CustomUsersAdapter adapter = new CustomUsersAdapter(getActivity(), arrayOfUsers);
mList.setAdapter(adapter);

Here also I tried using mList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); but it is not working

1

There are 1 best solutions below

3
K M Rejowan Ahmmed On

The list item layout that you are using (android.R.layout.simple_list_item_1) does not contain a RadioButton, which is why you aren't seeing any RadioButton in your list.

If you want to display a RadioButton for each item in the ListView, you'll need to use a different layout. Android provides a built-in layout for this: android.R.layout.simple_list_item_single_choice.

You can replace android.R.layout.simple_list_item_1 with android.R.layout.simple_list_item_single_choice in your ArrayAdapter.

ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
    android.R.layout.simple_list_item_single_choice, items);
mList.setAdapter(adapter);