1

I am in the process of learning Android development and I intend to show in a ListView any connected/paired Bluetooth devices. Each list item has a device name on the left and a switch on the right. Screenshot is a little big

ConnectedDevicesActivity visual end result

I have the design for how each Item will be shown in a separate bluetooth_device_entry.xml file.

The bluetooth_device_entry.xml file is layed out with the RelativeLayout and it has two children TextView and Switch

In the main layout XML file activity_connected_devices.xml I have a ListView that I populate programatically with the bluetooth_device_entry.xml file.

My problem is in the Java activity ConnectedDevicesActivity.java. I am able to attach a setOnItemClickListener to the ListView items but even after inflating the bluetooth_device_entry.xml the setOnChangeListener() attatched to the inflated layout Switch is not getting triggered.

bluetoothConnectedDeviceItemClickListener works but switchCheckedListener doesn't.

Any idea how to resolve this? Thanks.

bluetooth_device_entry.xml

(What to populate each ListView item with)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/bluetoothDeviceEntryLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:descendantFocusability="blocksDescendants">

    <TextView
        android:id="@+id/connectedDeviceName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/light_grey"

        android:paddingBottom="12dp"
        android:paddingEnd="8dp"
        android:paddingStart="8dp"
        android:paddingTop="12dp"
        android:text="@string/txtPlaceHolderConnectedBluetoothText"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="@dimen/dimen_listTextSizeMedium" />

    <Switch
        android:id="@+id/deviceStateSwitch"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_alignBaseline="@+id/connectedDeviceName"
        android:layout_alignBottom="@+id/connectedDeviceName"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="15dp"
        android:switchMinWidth="@dimen/dimen_switchWidth" />

</RelativeLayout>

activity_connected_devices.xml

(Activity initially loaded by the ConnectedDevicesActivity.java in onCreate())

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activityConnectedDevicesLinearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txtTitleConnectedDevices"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@color/dark_blue"
        android:gravity="center"
        android:text="@string/txtConnectedDevices"
        android:textColor="@color/light_blue"
        android:textSize="@dimen/dimen_buttonTextSize" />

    <ListView
        android:id="@+id/bluetoothConnectedDevicesListView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3" />
</LinearLayout>

ConnectedDevicesActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.Toast;

public class ConnectedDevicesActivity extends AppCompatActivity
{
    ListView bluetoothConnectedDevicesListView;
    Switch deviceSwitch;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connected_devices);
        setTitle("Connected Devices");

        bluetoothConnectedDevicesListView = findViewById(R.id.bluetoothConnectedDevicesListView);

        showConnectedBluetoothDevices();
    }

    public void showConnectedBluetoothDevices()
    {
        String[] connectedBluetoothDevices = new String[10];
        for(int i=0; i<connectedBluetoothDevices.length; i++)
        {
            connectedBluetoothDevices[i] = "Device " + (i+1);
        }


        ArrayAdapter<String> connectedBluetoothDevicesAdapter =
                new ArrayAdapter<String>(this,
                        R.layout.bluetooth_connected_devices_entry,
                        R.id.connectedDeviceName,
                        connectedBluetoothDevices);

        bluetoothConnectedDevicesListView.setAdapter(connectedBluetoothDevicesAdapter);
        bluetoothConnectedDevicesListView.setOnItemClickListener(new bluetoothConnectedDeviceItemClickListener());

        View inflatedView = getLayoutInflater().inflate(R.layout.bluetooth_connected_devices_entry, null);
        deviceSwitch = inflatedView.findViewById(R.id.deviceStateSwitch);

        /* This is not responding to switch loaded from inflated view */
        deviceSwitch.setOnCheckedChangeListener(new switchCheckedListener());

        Toast.makeText(
                ConnectedDevicesActivity.this,
                String.format("Switch checked? %b", deviceSwitch.isChecked()),
                Toast.LENGTH_SHORT).show();
    }

    public class bluetoothConnectedDeviceItemClickListener implements OnItemClickListener
    {
        /* When the user taps an item in the list view */
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Toast.makeText(
                    ConnectedDevicesActivity.this,
                    String.format("You tapped %s", bluetoothConnectedDevicesListView.getItemAtPosition(position)),
                    Toast.LENGTH_SHORT).show();
        }
    }
    /* When the user toggles a switch */
    public class switchCheckedListener implements CompoundButton.OnCheckedChangeListener
    {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            Toast.makeText(
                    ConnectedDevicesActivity.this,
                    String.format("Checked state is %s", isChecked),
                    Toast.LENGTH_SHORT).show();
        }
    }
}
FlashspeedIfe
  • 368
  • 1
  • 6
  • 15

1 Answers1

3

You are inflating an extra view which has no connection with your ListView's items

 bluetoothConnectedDevicesListView.setAdapter(connectedBluetoothDevicesAdapter);
 bluetoothConnectedDevicesListView.setOnItemClickListener(new bluetoothConnectedDeviceItemClickListener());

 View inflatedView = getLayoutInflater().inflate(R.layout.bluetooth_connected_devices_entry, null);
 // ^^^^^^^^ totally a new item, has no relation with views inside list
 deviceSwitch = inflatedView.findViewById(R.id.deviceStateSwitch);

 deviceSwitch.setOnCheckedChangeListener(new switchCheckedListener());

Solution : You need to create a customize Adapter and which will be responsible for providing every single rowitem view and inside getView you can apply operations (attaching listeners/manipulating values) on child views in you rowitem views.

Note: you will also required to manage a list to keep the track of switch view state because adapter recreates|reuse views.

Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
  • I'll give that a go – FlashspeedIfe Nov 12 '17 at 19:42
  • Your answer helped. I was able to get the `switchCheckedListener` to work by creating a custom adapter. Any ideas how to detect the index position of a switch? Right now with the `onCheckedChanged` I can't see a way to get the position or properties of that specific switch that was toggled. – FlashspeedIfe Nov 13 '17 at 00:24
  • 1
    @FlashspeedIfe [you can use tags or fetch the position using views](https://stackoverflow.com/questions/20541821/get-listview-item-position-on-button-click) – Pavneet_Singh Nov 13 '17 at 04:35