2013-08-06 23 views
0

嗨,大家好我是Android編程的新手,但對.net有一些經驗,無論如何我想要做的就是創建一個類,然後從一個活動調用這個類。通常,在.net中,我會用:如何用自定義值開始一個活動

RestartDialog rd = new RestartDialog(); 

rd.setType(EXTENDED_TYPE); 
rd.show; 

那麼這將在擴展模式下啓動然而,在Android的,你需要的Intent啓動activitys,這是唯一的辦法是嗎?我知道我可以使用Intent.putExtra等,但我需要先設置許多值。

爲了達到這個目的,我最好的辦法是什麼?在此先感謝您的幫助。

回答

1

意圖是發送數據的方式。所以萬一你必須發送很多數據,你可以使用Parcelable。它也是更快的方式..

如果你只是傳遞物體,那麼Parcelable就是爲此設計的。與使用Java的本地序列化相比,它需要更多的努力才能使用,但速度更快(我的意思是說,WAY更快)。

從文檔,對於如何實現一個簡單的例子是:

// 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(); 
    } 
} 

Observe that in the case you have more than one field to retrieve from a given Parcel, you must do this in the same order you put them in (that is, in a FIFO approach). 

Once you have your objects implement Parcelable it's just a matter of putting them into your Intents with putExtra(): 
Intent i = new Intent(); 
i.putExtra("name_of_extra", myParcelableObject); 

Then you can pull them back out with getParcelableExtra(): 
Intent i = getIntent(); 
MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra"); 

您也可以使用GSON發送數據..

+0

謝謝你隊友我會看看Parcelable。 – user2655267

+0

樂意幫忙:) – Sushil

1

首先,你需要創建一個Intent

Intent intent = new Intent(); 

想到一個意圖,以此來存儲數據值:

intent.putExtra("type", EXTENDED_TYPE); 

當你完成了你的意圖把信息,您啓動活動:

startActivity(intent); 

然後,在你的新的活動,您提取您在onCreate方法需要的值:

... 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.email_login_activity); 

    Intent intent = getIntent(); 
    this.type = intent.getIntExtra("type", 0); 

在這種情況下,如果未設置額外的「類型」,我已使getIntExtra返回0

讓我知道如果您有任何其他問題。

0

雖然最簡單的解決方案是:

要創建一個類與靜態數據成員與getters設置。

從一個活動中設置並從另一個活動中獲取該對象。

活動A mytestclass.staticfunctionSet(「」,「」,「」等等。

活動b mytestclass obj = mytestclass.staticfunctionGet();

+0

這似乎是一個簡單的解決方案太謝謝。 – user2655267

+0

高興地幫助:) – Sushil

相關問題