2010-07-12 88 views
1

我使用對話框作爲用戶輸入數據的窗體。當他們點擊「確定」按鈕時,對話框關閉,我需要使用輸入的數據。一旦對話框關閉,我怎樣才能在活動中引用這些數據?從對話框返回數據

回答

5

獲取它,當用戶按下「確定」按鈕

final EditText input = new EditText(this); // This could also come from an xml resource, in which case you would use findViewById() to access the input 

AlertDialog.Builder builder = new AlertDialog.Builder(this); 
builder.setView(input); 
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface dialog, int whichButton) { 
     String value = input.getText().toString(); 
     mItem.setValue(value); // mItem is a member variable in your Activity 
     dialog.dismiss(); 
    } 
}); 
4

指定一個OnDismissListener到對話框並將數據傳遞給那裏的活動。

或者,您可以創建對話框活動並將數據作爲活動結果返回。請參閱以下鏈接瞭解更多信息有關啓動活動和gettings結果:

http://developer.android.com/reference/android/app/Activity.html#StartingActivities

+0

如果拿OP的問題從字面上(「如何我可以在對話結束後在活動中引用這些數據嗎?「),那麼這是比我更好的答案。但我認爲OP實際上有能力在對話框關閉之前訪問輸入*,從而無需使用OnDismissListener。 – idolize 2010-07-12 21:48:54

+0

我強調使用帶有對話框主題的活動的建議。除非它只是一個沒有驗證的字段,否則從長遠來看,把表單邏輯放在對話框中是一個壞主意。 – hpique 2010-07-12 22:26:34

+0

一個有效的點,特別是如果該對話框將在任何其他活動中重用。 – idolize 2010-07-13 14:54:29