如何在Android中使用setter和getter存储全局变量



我是Android开发的新手,我试图在两个活动中使用全局变量。那么,如何使用Setter和Getter进行相同的操作呢?或者,还有更好的方法?请帮助我!提前致谢!Sidharth

用于全局变量:

  1. 使用可以使用sharedPreference,它将保存值,直到您卸载应用程序,并且可以使用上下文中的任何地方访问应用程序。

  2. 扩展应用程序类,并在其中声明全局变量并添加getter和setter方法。

在您的活动中:

    YourApplication yourApplication = (YourApplication) getApplicationContext();
    yourApplication.setGlobalValue(10);
    yourApplication.getGlobalValue();

创建类:

 class YourApplication extends Application {
    private Integer globalValue;
    public Integer getGlobalValue() {
        return globalValue;
    }
    public void setGlobalValue(Integer value) {
        globalValue = value;
    }
}

最简单的方法是将变量传递给您用来开始活动的意图中的第二个活动:

Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("variableKEY", variable);
startActivity(intent)

访问下一个活动的意图

String s = getIntent().getStringExtra("variableKEY");

意图文档具有更多信息(请查看标题为" Extras"的部分)。

从这里

最新更新