togglebutton.isChecked()不起作用?

时间:2014-07-14 15:21:26

标签: java android togglebutton

我正在使用Arduino并尝试使用两个切换按钮来连接和启用Arduino。在连接机器人之前,我不想按下启用按钮。这是我的主要活动:

public class MainActivity extends Activity {

Arduino arduino = null;
ToggleButton enable, connect;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ToggleButton connect = (ToggleButton) findViewById(R.id.buttonConnect);
    ToggleButton enable = (ToggleButton) findViewById(R.id.buttonEnable);

}

public void onToggleClicked(View view) {


    switch(view.getId()) {

        case R.id.buttonConnect:

            boolean on = ((ToggleButton) view).isChecked();

            if(on){

                //Take the text from editText1 and make it the IP Address
                EditText text = (EditText)findViewById(R.id.editText1);
                String ip = text.getText().toString();
                arduino = new Arduino(ip);

                arduino.connect();

                arduino.disable();

            } else {

                arduino.disable();
                arduino.disconnect();
                enable.setChecked(false);
            }
        break;  



        case R.id.buttonEnable:

            boolean click = ((ToggleButton) view).isChecked();

            if(click && connect.isChecked()) {

                arduino.enable();

            }else {

                System.out.println("Not Connected");
                enable.setChecked(False);
                arduino.disable();
            }
        break;  

        default:

        break;  

        }

    }

我知道程序没有到达buttonEnable案例中的else语句,因为它没有打印出来" Not Connected。"我也尝试在我的if语句中使用connect.isEnabled(),但这也不起作用。有人有答案吗?谢谢!

1 个答案:

答案 0 :(得分:0)

尝试设置单击侦听器以将代码执行附加到您按钮