Toggle Button not doing anything when clicked

83 views Asked by At

I'm trying to use a ToggleButton inside my Android code, but it seems that it does nothing within it and I don't know what I'm doing wrong. Does anyone know what I'm doing wrong?

Here it is the code:

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

There are 2 answers

2
Simas On BEST ANSWER

Why don't you call your onToggleClicked method?

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();
        }
    });
}
0
codeMagic On

You haven't set the onClick in your xml within your ToggleButton.

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

Docs

That is a user-defined method so you need to tell your Button to use that method (it could be named whatever you want). The docs link above also explains how to use the OnCheckedChangeListener if you prefer.

side-note: I think you want if (on) instead of if (true)