gpt4 book ai didi

android - 如何广播变量值并接收它?

转载 作者:行者123 更新时间:2023-11-29 16:16:04 25 4
gpt4 key购买 nike

我正在制作一个应用程序,我想在其中广播单击按钮时的变量值。同时我想在其他 Activity 中接收这个值并显示它。我应该怎么做?

最佳答案

在我看来你可以使用全局变量,它可以跨 Activity 使用。(也回答了一些未提出的问题;))

同样,你可以扩展android.app.Application类,

Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.


示例来自 Another question ,

public class MyApplication extends Application {

private String someVariable;

public String getSomeVariable() {
return someVariable;
}

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

然后在您的 Activity 中,您可以像这样获取和设置变量:

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

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

如示例中所示,设置您的变量来自一个 Activity (或按钮点击任何)并获取另一个 Activity 中的值。

关于android - 如何广播变量值并接收它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9463429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com