2010-12-13 38 views
1

如何從另一個活動調用方法? 在我的主要活動中,我有一個按鈕,顯示一個對話框來設置遊戲的難度級別。 然後你點擊開始遊戲,開始一個包含所有遊戲信息的視圖的新活動。 我需要發送難度級別選擇到其他活動,但似乎無法弄清楚如何。來自其他活動的Android調用方法

回答

6

你可以把它與意圖的演員:

Intent StartGame = new Intent(this, StartGame.class); 
StartGame.putExtra("difficulty", difficultyLevel); 
startActivity(StartGame); 

然後在你的StartGame.class你可以retrive像這樣(假設它是一個字符串):

Bundle extras = getIntent().getExtras(); 
if (extras != null) { 
    String difficulty= extras.getString("difficulty"); 
} 
+0

哦,哇,謝謝! – semajhan 2010-12-13 23:05:25

+0

我這樣做的方式atm,但沒有其他方式嗎?因此,您可以直接從啓動意圖的活動中調用方法,而不是首先在目標活動中檢查GetExtras(),然後調用方法。 – Vincent 2011-04-27 09:33:11

6

嗯,我不知道我的解決方案有多健全,但是我創建了一個myApplication類,它對Application類進行了子類化。

這個擁有引用了活動我想叫

import android.app.Application; 

public class myApplication extends Application { 
    public PostAndViewActivity pv; 
} 

當PostAndViewActivity調用的OnCreate是設置PV爲指向自身。

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    ((myApplication) getApplication()).pv = this; 

然後,當我想打電話給我要我只是用這樣的代碼的方法:

((myApplication) getApplication()).pv.refreshYourself(); 

也許有點哈克,但它的作品..... 我歡迎一些的批評此;-)