简体   繁体   中英

How to change Switch/toggle button state from another activity

Ive done something like this. Im receiving 'true' value from 2nd activity and when i receive that it should change my switch button state to OFF. Becouse we need to put manually switch to ON possition. I think it should work but it didnt

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker);
        //ToggleButton alarmToggle = (ToggleButton) findViewById(R.id.alarmToggle);

        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

        final Switch sswitch = (Switch) findViewById(R.id.alarmToggle);
        sswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean val) {
                val = getIntent().getBooleanExtra("toggleBtn", false);
                if(val)
                 {
                    sswitch.setChecked(false);
                }

            }
        });
    }

In 2nd activity as i said im sending that value to the first one

 public void backtomain(View view)
    {
        Intent intent = new Intent(this, AalarmActivity.class);
        intent.putExtra("toggleBtn", true);
        finish();

    }

You can do it as you are asking if isChecked on your first if, with :

((ToggleButton)view).isChecked();

Then in your Intent put this :

intent.putExtras("toggleBtn", ((ToggleButton)view).isChecked());

EDIT

Acording on your code it will only make the Intent when the ToggleButton is true, isnt' it? Then if it enters on the if it means that the ToggleButton is enabled, so instead of pass ((ToggleButton)view).isChecked() on your putExtras you can pass true instead, then make an else and putting it to false

EDIT 2

I think you forgot the startActivity() on :

Intent intent = new Intent(this, AalarmActivity.class);
intent.putExtra("toggleBtn", true);
startActivity(intent);
finish();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM