2011-12-25 101 views

回答

8

此代碼是近似值,因爲我是從內存中寫入它的。

Intent mIntent = new Intent(ActivityA.this, ActivityB.class); 
mIntent.putLong(KEY, getTimeMilliseconds()); 
startactivity(mIntent); 
在ActivityB的OnCreate

然後:

Bundle mBundle = getItent().getExtras(); 
Long time = mBundle.getLong(KEY); 

注:

putLong/getLong可以適用於多種類型的字符串,整數...

如果你想它適用於一個自定義對象,你應該使該對象 實現Parcelable。

+0

我需要傳遞給另一個類,但不是一個活動......任何人可以請請明確點??? – subrussn90 2011-12-26 05:34:45

+0

你需要你的對象來實現parcelable [Parcelable Example](http://stackoverflow.com/a/8653518/794291)。一旦你的對象做到了,你可以使用bundle來傳輸它。 – Rick 2011-12-28 08:58:48

2

通行證,代表着捆綁例如你的約會長期價值long time = new Date()。getTime();

7

日期是序列化的,所以你可以使用get/putSerializable

MyFragment fragment = new MyFragment(); 
Bundle bundle = new Bundle(); 
bundle.putSerializable(MyFragment.DATE_KEY, new Date()); 
fragment.setArguments(bundle); 

MyFragment

public void onViewStateRestored(Bundle savedInstanceState) { 
    super.onViewStateRestored(savedInstanceState); 
    Bundle bundle = savedInstanceState != null ? savedInstanceState : getArguments(); 
    Date startTime = (Date) bundle.getSerializable(MyFragment.DATE_KEY); 
    this.time = startTime; 
} 

public void onSaveInstanceState(Bundle bundle) { 
    super.onSaveInstanceState(bundle); 
    bundle.putSerializable(MyFragment.DATE_KEY, this.time); 
}