单击时切换按钮不执行任何操作

时间:2014-11-20 17:44:28

标签: android buttonclick android-togglebutton

我正在尝试在我的Android代码中使用ToggleButton,但似乎它内部没有任何内容,我不知道我做错了什么。有谁知道我做错了什么?

这是代码:

public class StartActivity extends ActionBarActivity {   Toast t;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);

    }       public void onToggleClicked(View view) {
        boolean on = ((ToggleButton) view).isChecked();
        if (true) {

            t=Toast.makeText(getApplicationContext(), "Anesthesia has started",Toast.LENGTH_SHORT);
            t.show();
            Intent b_1=new Intent(StartActivity.this,TestService.class);
            startService(b_1);

        } else {
             t=Toast.makeText(getApplicationContext(), "Anesthesia has ended",Toast.LENGTH_SHORT);
            t.show();

        }   }

2 个答案:

答案 0 :(得分:1)

为什么不打电话给你onToggleClicked方法?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start);
    ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton);
    onToggleClicked(toggle);

    // Or set a listener that will be called every time the toggle is changed:
    toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            Toast.makeText(getApplicationContext(), "Toggle set to: " + b,
                    Toast.LENGTH_SHORT).show();
        }
    });
}

答案 1 :(得分:1)

您尚未在onClick内的xml中设置ToggleButton

<ToggleButton
    ...
    android:onClick="onToggleClicked"/>

Docs

这是一个用户定义的方法,因此您需要告诉您的Button使用该方法(可以根据需要命名)。上面的文档链接还说明了如果您愿意使用OnCheckedChangeListener

旁注:我认为您希望if (on)代替if (true)