我今天正在做一些 android 代码,现在的问题是我需要让变量通过。场景是我需要先登录 facebook 然后获取我的信息。之后出现一个启动屏幕,它将使用意图显示我的姓名等信息。之后主屏幕现在将出现,并且来自初始屏幕的所有数据现在也将使用意图传递到主屏幕,但问题是这个主屏幕只是我的 tabViews 的容器,我可以随时从一个页面到另一个,我认为我没有必要在这部分再次使用意图。现在我需要获取所有传递到主屏幕的传递数据到我的一个选项卡并将其显示在 TextView 上。
6 回答
您可以android.app.Application
为此目的使用该类。
创建和使用 Application 类的步骤:
创建您的应用程序类。一个例子如下所示:
public class ApplicationController extends Application { //Application wide instance variables //Preferable to expose them via getter/setter methods @Override public void onCreate() { super.onCreate(); //Do Application initialization over here } //Appplication wide methods //Getter/Setter methods }
在中指定您的应用程序类
AndroidManifest.xml
<application android:icon="@drawable/icon" android:label="@string/app_name" android:name=".ApplicationController">
获取Application Class实例的实例并调用各种方法:
ApplicationController AC = (ApplicationController)getApplicationContext();
希望这可以帮助。
为此,请在主屏幕中使用公共静态变量。或者您也可以为此目的使用Application类。其他选项是SharedPreferences。
对于应用程序类全局变量,请查看这个 SO 问题如何在 Android 中声明全局变量?
将变量定义为公共静态或其他选项是将变量的值存储到共享首选项中并在下一个活动中检索首选项的值,并参考下面的链接以获取更多信息。
您可以使用 SharedPreferences 像这样传递值:
//for write id one Activity
SharedPreferences spre = context.getSharedPreferences("Your prefName",
Context.MODE_PRIVATE);
SharedPreferences.Editor prefEditor = spre.edit();
prefEditor.putString("key", value);
prefEditor.commit();
// for get id second Activity
SharedPreferences spre = context.getSharedPreferences("Your prefName",
Context.MODE_PRIVATE);
String mystring= spre.getString("key","");
假设第一类是A,另一个类是B,您想将数据从A发送到B,即您想将user_id从A类发送到B,然后在您的A类中将user_id声明为公共字符串。在 B 类中以 id = A.user_id 访问您的 user_id。
希望这对您有所帮助。