[英]Android - One class used by multiple activities
我有一个类来管理从文件中加载的数据。 此类在主Activity中初始化。 当主活动创建一个新活动时,新活动需要文件中的数据,换句话说,它需要对管理数据的类的引用。 最好的方法是什么?
是的,最好的方法是只创建类的一个instance
。 这是Singleton设计模式。
singleton
模式应满足您的需求。 基本上,这是一个只能实例化一次并管理该实例本身的类,因此您可以从任何地方获取它。
这样的教程将帮助您入门: http : //portabledroid.wordpress.com/2012/05/04/singletons-in-android/
如果一个类仅表示它从文件中读取的数据块,那么将您的类设为单例并没有错,如下所示:
class FileData {
private static final FileData instance = readFile();
public static FileData getInstance() {
return instance;
}
private static readFile() {
... // Read the file, and create FileData from it
}
public int getImportantNumber() {
return ...
}
}
现在,您可以引用所有其他类的数据,如下所示:
FileData.getInstance().getImportantNumber();
1 .:单例模式
2:您可以使该类为Parcelable。
// simple class that just has one member property as an example
public class MyParcelable implements Parcelable {
private int mData;
/* everything below here is for implementing Parcelable */
// 99.9% of the time you can just ignore this
public int describeContents() {
return 0;
}
// write your object's data to the passed-in Parcel
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
然后,您就可以通过意图发送对象:
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
然后像这样在您的第二个活动中获取它:
Intent i = getIntent();
MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");
为方便起见,我把代码从这个 SO线程,因为它是相当不错的,但也是非常基本的,但。 您甚至可以通过Intents发送对象列表,但这有点复杂,并且需要更多示例代码和说明。 如果那是您的目标,请询问。 对于一个对象,代码是完全可以的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.