[英]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.
因为我们需要手动将开关切换到ON位置。 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 : 您可以在询问第一个条件是否为
isChecked
时执行以下操作:
((ToggleButton)view).isChecked();
Then in your Intent
put this : 然后在您的
Intent
放入:
intent.putExtras("toggleBtn", ((ToggleButton)view).isChecked());
Acording on your code it will only make the Intent
when the ToggleButton
is true, isnt' it? 根据您的代码,仅当
ToggleButton
为true时,它才会产生Intent
,不是吗? 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
然后如果在on上输入,
if
表示已启用ToggleButton
,因此可以代替传递((ToggleButton)view).isChecked()
在您的putExtras
上传递true
,然后进行else
并将其设置为false
I think you forgot the startActivity()
on : 我认为您忘记了
startActivity()
:
Intent intent = new Intent(this, AalarmActivity.class);
intent.putExtra("toggleBtn", true);
startActivity(intent);
finish();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.