2012-03-13 18 views
0

我需要創建一個邏輯來減少Android項目中的代碼大小。假設我有一個活動C.活動C有一個TextView,其值爲「Hello」。還有另外兩個活動A & B.現在,如果按鈕上的活動A單擊調用活動C,那麼TextView的值必須更改爲「您好嗎?」。如果活動B調用活動C,則TextView值將爲「我很好」。如何根據不同的Activites調用第一個活動來更改活動的TextView的值?

所以,我的問題是,如何檢測哪個Activity正在調用Activity C並相應地在運行時更改TextView的文本?

任何形式的幫助將不勝感激。

回答

2

除了其他答覆。您可以只發送短信的文本,並刪除活動C中的條件檢查。

呼叫活動的C:

Intent i = new Intent(this, ActivityC.class); 
i.putExtra(ActivityC.MESSAGE_KEY, "How are you?"); 
startActivity(i); 

Intent i = new Intent(this, ActivityC.class); 
i.putExtra(ActivityC.MESSAGE_KEY, "I am fine"); 
startActivity(i); 

而在ActivityC:

public final static String MESSAGE_KEY = "com.package.name.ActivityC.message"; 

@Override 
protected void onCreate() { 
    ... 
    String message = getIntent().getStringExtra(MESSAGE_KEY); 
    if (message != null) { 
     textView.setText(message); 
    } 
    ... 
} 
0

你可以讓調用活動發送一個包含意圖的包以及其中的調用活動的名稱。

被調用的活動然後可以讀取該包的內容以知道哪個活動調用了它並相應地顯示數據。

0

你可以發送額外的意圖在開始活動。

當你的B

add intent.PutExtra("VARIABLE NAME","called from B"); 

調用它,如果從A

add intent.PutExtra("VARIABLE NAME","called from A"); 

調用,可以通過

String calledFrom = getIntent().getStringExtra("VARIABLE NAME"); 

你可以檢查得到您的活動C這個變量的值一樣稱爲從所調用的字符串值開始。

0

可以傳遞之間活動

Intent intent = new Intent(A.this,C.class); 

因爲意圖需要兩個參數 語境與類refreing到數據的預期開始活動 befor分級startActivity();方法只是在C活性增加一個整數指的類

intent.putExtra("src",1); 

Intent intent = getIntent(); 
if (intent.getExtra("src").equals("1")) 
textView.setText("how are you?") 
else if (intent.getExtra("src").equals("2")) 
textView.setText("fine thanks") 
0

你需要一些數據發送到活動ç這樣你就可以處理誰在調用這個C活性:

Intent i = new Intent(this , C.class); 
i.putExras("from" , "a"); 
startActivity(i); 

Intent i = new Intent(this , C.class); 
i.putExras("from" , "b"); 
startActivity(i); 

在活動C上,您需要讀取這些值並像這樣檢查:

onCreate(){ 

String from = getIntent().getStringExtras("from"); 

if(from.equals("a")){ 
//came from a 
} else if(from.equals("b")){ 
//came from b 
} 

} 
相關問題