如何在Android中获得切换值?

Chi*_*ria 13 android

我在Main Activity中放置了一个switch小部件,我还有第二个扩展BroadcastReceiver的活动.我想在第二个活动中获得switch小部件的布尔状态.

如果我输入

Switch s = (Switch) findViewById(R.id.switch1);
Run Code Online (Sandbox Code Playgroud)

它表示对于SecondActivity类型未定义findViewById.问题是Android不允许我在扩展Broadcast Receiver的类中获得switch的值.

我想知道开关的状态,即开关是打开还是关闭,但是在第二个活动中.我怎样才能实现它?

Jst*_*wll 19

findViewById()从Activity 调用只能访问属于该Activity布局的视图.您无法使用它来搜索任何其他活动的布局.

根据您的应用程序设计,您可以使用以下方法之一:

1)通过Intent extra将Switch的值发送到SecondActivity

在活动中:

Intent mIntent = new Intent(this, SecondActivity.class);
mIntent.putExtra("switch", s.isChecked());
startActivity(mIntent);
Run Code Online (Sandbox Code Playgroud)

在SecondActivity中:

boolean isChecked = getIntent().getBooleanExtra("switch", false);
Run Code Online (Sandbox Code Playgroud)

2)在更改时将值保存到首选项,并在SecondActivity中读取首选项

在活动中:

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

在SecondActivity中:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
boolean isChecked = settings.getBoolean("switch", false);
Run Code Online (Sandbox Code Playgroud)


Alé*_*lho 6

要访问交换机的值,您需要执行以下操作:

((Switch) findViewById(R.id.switch_id)).isChecked();
Run Code Online (Sandbox Code Playgroud)

但是BroadcastReceiver的上下文中,您无法真正访问布局,因此无法访问交换机.您必须在活动中执行此操作,该活动会扩展具有Switch的布局.

您可以在Activity中以编程方式注册BroadcastReceiver,这是我看到这些概念混合的唯一方法.