I would like to display a list of paired Bluetooth devices and let the user select one. I’m trying to create a two-line list view (one line for the friendly device name, the other for the MAC address) with radio buttons.
To this end I have copied simple_list_item_2_single_choice.xml into my project and create my list view with the following code:
listView = new ListView(activity);
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
ArrayAdapter<BluetoothDevice> listViewAdapter = new ArrayAdapter<BluetoothDevice>(activity,
R.layout.simple_list_item_2_single_choice, android.R.id.text1) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView text1 = (TextView) view.findViewById(android.R.id.text1);
TextView text2 = (TextView) view.findViewById(android.R.id.text2);
text1.setText(getItem(position).getName());
text2.setText(getItem(position).getAddress());
return view;
}
};
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
// addAll() is not supported on APIs below 11
for (BluetoothDevice device : devices)
listViewAdapter.add(device);
listView.setAdapter(listViewAdapter);
This displays the list the way I want it, but I can’t select any items (the radio button stays empty when I tap an item). What gives?
Not sure how this worked in AOSP (they might use non-standard logic for the layout), but with a standard list view the key is that the root item of the View must implement the Checkable interface.
So, based on this answer, I did the following:
With these changes it works as intended. I can check items by tapping them, and the items will behave like a group of radio buttons.