切换按钮不切换在Android
问题描述:
我有开关按钮类,像这样定义的:切换按钮不切换在Android
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;
}
}
当我运行的应用程序,并切换B2
,我总是得到的送别结果部分如果,即使在xml中,切换按钮声明为false,并且按钮不会打开或关闭。
这是怎么发生的?
答
ToggleButton
s,像所有的CompoundButton
一样,在点击时照顾自己的检查状态。您的OnClickListener
正在抵消该行为。相反,请使用CompoundButton.OnCheckedChangeListener
,并检查传入onCheckedChanged()
的boolean
是否为新状态。
答
我建议您在切换按钮上使用检查更改的侦听器。
ToggleButton b2 = (ToggleButton) findViewById(R.id.button2);
b2.setBackgroundColor(Color.GRAY);
b2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
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 {
// The toggle is disabled
}
}
});
由于没有看到您的XML,这听起来像onClick方法也没有被单击按钮时被调用。
太棒了!扩展了正确的类,实现了方法,取代了buttonView,并注释掉了我的手动切换。现在唯一的问题是它们应该根据xml开始为false,但是在第一次点击时,我得到了发送关闭结果,这发生在b2.isChecked()条件为真时发生。 – marciokoko
这听起来对我来说是正确的。如果'Button'以_off_开头,第一次点击就会切换到_on_('isChecked()= true'),所以你的'if'块会被执行。在状态发生变化后,'onCheckedChanged()'方法会被触发,因此您可能需要将自己的逻辑从“OnClickListener”中取消。 –