2010-07-22 35 views
0

我在Android開發新的,我有一個問題,當我創建我的新的活動。行動之前startActivity()

我想用我的活動之前啓動它。例如,我嘗試過:

MyActivity menu = new MyActivity(); 
menu.setXmppreception(reception); 
Intent intent = new Intent(Screen.this,MyActivity.class); 
Screen.this.startActivity(intent); 

但是,我的「菜單」和「MyActivity.class」不是同一個實例。因此我已經嘗試:

MyActivity menu = new MyActivity(); 
menu.setXmppreception(reception); 
Intent intent = new Intent(Screen.this,menu); 
Screen.this.startActivity(intent); 

但它不工作... 你有一個解決方案,幫助我嗎?

感謝您的幫助和抱歉不好英語。

回答

2

你不能做到這一點像你想,如果你正在尋找您必須使用額外的活動之間傳遞數據,並可以通過只序列化項目。

第一情境(可活動/服務等)

您有幾種選擇:

1)使用BundleIntent

Intent mIntent = new Intent(this, Example.class); 
Bundle extras = mIntent.getExtras(); 
extras.putString(key, value); 

2)創建新的捆綁

Intent mIntent = new Intent(this, Example.class); 
Bundle mBundle = new Bundle(); 
mBundle.putString(key, value); 
mIntent.putExtras(mBundle); 

3)使用意向

putExtra()快捷方法
Intent mIntent = new Intent(this, Example.class); 
mIntent.putExtra(key, value); 

新的上下文(可以是活動/服務等)

Intent myIntent = getIntent(); // this getter is just for example purpose, can differ 
if (myIntent !=null && myIntent.getExtras()!=null) 
    String value = myIntent.getExtras().getString(key); 
} 

注:捆綁有 「得」 與「放入「所有基本類型,Parcelables和Serializables的方法。我只是將Strings用於示範目的。

+0

我想我會使用第三個選項(putExtra()方法)。如果我理解了所有的東西,我必須在我的XMPPReception類中實現「Serializable」,不是嗎? 再次感謝。 – 2010-07-22 09:06:43

+0

大概ye'' reception'必須是可序列化的,但Eclipse會告訴你。 – Pentium10 2010-07-22 09:47:16

1

你不必自己創建新的活動,Android系統會爲你。 如果你想從Screen ActivityMyActivity,你可以這樣做:

Intent intent = new Intent(Screen.this,MyActivity.class); 
startActivity(intent); 

,然後在你MyClass的java文件,在onCreate方法,你可以這樣做:

this.setXmppreception(reception); 

這樣,我想你會想要,不是嗎?

相關問題