如何从其他活动中检索布尔值?

问题描述 投票:0回答:2

我有一个活动将各种变量设置为true或false,以用作其他活动的设置。我需要能够在其他活动中调用这些变量的状态,但是我不知道怎么做。我知道可以使用的字符串

getApplicationContext().getResources().getString(R.string.stringName);

但是对于Boolean,同一件事将不起作用。建议有人使用

activityName.variableName

但是那也不行。有什么建议吗?

java android android-studio
2个回答
1
投票

您可以使用很多最常见的两种方法来创建全局变量

[1-使用Application

public class MyApplication extends Application {

    private String someVariable;

    public String getSomeVariable() {
        return someVariable;
    }

    public void setSomeVariable(String someVariable) {
        this.someVariable = someVariable;
    }
}

请确保不要在manifest文件中声明

<application 
  android:name=".MyApplication" 
  android:icon="@drawable/icon" 
  android:label="@string/app_name">

如何使用?

// set
((MyApplication) this.getApplication()).setSomeVariable("foo");

// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();

2- 通过使用Extra作为变量,借助Intent将其从活动传递给其他人>]

Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);

要在第二活动中阅读,请使用

String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");

对于设置屏幕建议使用SharedPreference,您可以从here中学习如何使用


0
投票

代替static变量或application变量,而使用SharedPreference来实现这一点,该变量也将在应用程序关闭时持续存在。

© www.soinside.com 2019 - 2024. All rights reserved.