Search code examples
androidbuttonclickandroid-togglebutton

Toggle Button not doing anything when clicked


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();

        }   }

Solution

  • 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();
            }
        });
    }