[英]How can I use an array which is in a different class?
I have a 2D array set up in an activity and I want to call it into a fragment so I can use its contents. 我在一个活动中设置了一个2D数组,我想将其称为片段,以便可以使用其内容。 The array is called "Names".
该数组称为“名称”。 I do not understand the steps involved to do this.
我不了解执行此操作的步骤。
You may want to do some reading up on the Singleton Design Pattern . 您可能需要对Singleton设计模式进行一些阅读。 But in the mean time, I'll get you started.
但与此同时,我会让您开始。
Create a class "MyData" which will hold all of your variables/arrays that you want to share. 创建一个“ MyData”类,其中将包含您要共享的所有变量/数组。 Then you simply need a getter method to call the class.
然后,您只需要一个getter方法来调用该类。 Once this is done, you'll be able to access all your shared variables.
完成此操作后,您将可以访问所有共享变量。 :)
:)
Example MyData Class: 示例MyData类:
public class MyData
{
private static MyData _instance;
/* <Shared variables go here> */
public String sharedVariable = "yay this is shared!";
public String sharedVariable2 = "this is also shared!";
public String myArray[][];
/* </Variables> */
public static MyData getMyData()
{
if(_instance == null)
_instance = new MyData();
return _instance;
}
}
Example activity/fragment where you want to set the data: 您要在其中设置数据的示例活动/片段:
MyData data = MyData.getMyData();
data.myArray[0][0] = "test";
Example activity/fragment where you want to GET the data you set: 您想要获取所设置数据的示例活动/片段:
MyData data = MyData.getMyData();
String result = "";
result = data.myArray[0][0];
// result will now = "test"
By using this structure, if the MyData class is being called for the first time, it will create the instance, and if it HAS been called already, then it will simply return _instance which will contain all the variables you've set. 通过使用此结构,如果第一次调用MyData类,它将创建实例,如果已经调用了该实例,则它将简单地返回_instance,它将包含您设置的所有变量。
DISCLAIMER: When your app is minimized or left idle for a while, the android OS will clear all the variables in your class. 免责声明:当您的应用程序最小化或空闲一段时间后,Android OS会清除类中的所有变量。 You have three options to avoid this:
您有三种选择可以避免这种情况:
I usually go with option 3 as it usually fits my needs best. 我通常选择选项3,因为它通常最适合我的需求。
Good luck! 祝好运!
make your array public, then call from your fragment like 将您的数组公开,然后像这样从片段中调用
OtherActivity.array[]
OtherActivity.array []
You can perform all other operations as normal 您可以照常执行所有其他操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.