I have a class with toggle buttons defined like so:
public class DeviceControlActivity extends Activity implements View.OnClickListener
private ToggleButton b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gatt_services_characteristics);
b2 = (ToggleButton) findViewById(R.id.button2);
b2.setOnClickListener(this); // calling onClick() method
b2.setBackgroundColor(Color.GRAY);
b3 = (ToggleButton) findViewById(R.id.button3);
b3.setOnClickListener(this);
b3.setBackgroundColor(Color.GRAY);
@Override
public void onClick(View v) {
// default method for handling onClick Events..
switch (v.getId()) {
case R.id.button2:
// call writeCharacteristic but concatenate pin #
if (b2.isChecked()) {
b2.setChecked(false);
b2.setBackgroundColor(Color.GRAY);
// do code to send pin# with writeCharacteristic
String str = "Pin11,0" + "\n";
Log.d(TAG, "Sending OFF result=" + str);
/*final byte[] tx = str.getBytes();
if(mConnected) {
characteristicTX2.setValue(tx);
mBluetoothLeService.writeCharacteristic(characteristicTX2);
mBluetoothLeService.setCharacteristicNotification(characteristicRX2,true);
}*/
} else if (!b2.isChecked()) {
b2.setChecked(true);
b2.setBackgroundColor(Color.BLUE);
// do code to send pin# with writeCharacteristic
String str = "Pin11,1" + "\n";
Log.d(TAG, "Sending ON result=" + str);
/*final byte[] tx = str.getBytes();
if(mConnected) {
characteristicTX2.setValue(tx);
mBluetoothLeService.writeCharacteristic(characteristicTX2);
mBluetoothLeService.setCharacteristicNotification(characteristicRX2, true);
}*/
}
break;
}
}
when I run the app and toggle b2, I always get the Sending OFF result part of the if, even though in the xml the toggle buttons are declared as false and the button doesnt toggle on or off.
Why is this happening?
ToggleButton
s, like all CompoundButton
s, take care of their own checked state upon clicking. Your OnClickListener
is counteracting that behavior. Instead, use a CompoundButton.OnCheckedChangeListener
, and check the boolean
passed into onCheckedChanged()
for the new state.