[英]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.