如何在Android中得到开关值? [英] How to get switch value in Android?

查看:637
本文介绍了如何在Android中得到开关值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经把在主要活动开关部件,我也有一个扩展的BroadcastReceiver第二次活动。我想在第二个活动开关部件的布尔状态。

I have placed a switch widget in Main Activity, I also have a second activity that extends BroadcastReceiver. I want to get the boolean state of switch widget in second activity.

如果我键入

Switch s = (Switch) findViewById(R.id.switch1);

它说findViewById是未定义的类型SecondActivity。问题是Android不容许我得到扩展广播接收器一类开关的值。

it says findViewById is undefined for the type SecondActivity. The problem is Android doesn't allow me to get the value of switch in a class that extends Broadcast Receiver.

我想知道开关,即的状态,​​开关是否开启或关闭,但在第二个活动。我怎样才能实现呢?

I want to know the state of switch, i.e, whether switch is on or off, but in second activity. How can I achieve it?

推荐答案

调用 findViewById()从活动只能访问是,布局的一部分意见活动。你不能用它来搜索其他任何活动的布局。

Calling findViewById() from an Activity can only access Views that are a part of the layout of that Activity. You cannot use it to search the layout of any other Activity.

根据您的应用程序的设计,您可以使用其中的一个:

Depending on your app design, you can use one of these:

1),通过发送切换到SecondActivity的值的额外意图

在活动:

Intent mIntent = new Intent(this, SecondActivity.class);
mIntent.putExtra("switch", s.isChecked());
startActivity(mIntent);

在SecondActivity:

boolean isChecked = getIntent().getBooleanExtra("switch", false);

2)的值保存到变化的preference,并在SecondActivity阅读preferences

在活动:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor e = settings.edit();
e.putBoolean("switch", s.isChecked());
e.commit();

在SecondActivity:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
boolean isChecked = settings.getBoolean("switch", false);

这篇关于如何在Android中得到开关值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆