2013-06-02 26 views
3

我創建了一個帶有自定義AlertDialog的DialogFragment,我需要在我的應用程序的幾個點上顯示它。該對話框要求用戶輸入一些數據。等待對話框片段輸入的活動

我想找到一種方法來使對話框被調用的活動等待用戶輸入,然後在用戶按下ok按鈕時執行變量動作(或者如果他按下取消按鈕,則沒有任何動作)。

AFAIK在Android中沒有「模式對話框」,那麼實現這種(很平常的)類型行爲的正確方法是什麼?

+0

http://developer.android.com/training/basics/fragments/communicating.html – Tarun

回答

6

要允許片段與其活動進行通信,您可以在Fragment類中定義一個接口並在Activity中實現它。

public class MyDialogFragment extends DialogFragment { 
OnDialogDismissListener mCallback; 

// Container Activity must implement this interface 
public interface OnDialogDismissListener { 
    public void onDialogDismissListener(int position); 
} 

@Override 
public void onAttach(Activity activity) { 
    super.onAttach(activity); 

    // This makes sure that the container activity has implemented 
    // the callback interface. If not, it throws an exception 
    try { 
     mCallback = (OnDialogDismissListener) activity; 
    } catch (ClassCastException e) { 
     throw new ClassCastException(activity.toString() 
       + " must implement OnDialogDismissListener"); 
    } 
} 


    ... 
} 

在對話框中單擊OK監聽器添加

mCallback.onDialogDismissListener(position); 

在你的活動

public static class MainActivity extends Activity 
     implements MyDialogFragment.OnDialogDismissListener{ 
    ... 

    public void onDialogDismissListener(int position) { 
     // Do something here to display that article 
    } 
} 
+0

這似乎像一個合適的解決方案「位置」變量是否真的有必要? –

+2

沒有不必要..你可以傳遞你想要的任何東西..你只需要改變函數簽名。 – Tarun

+0

好的例子,正是我要找的東西 – IHeartAndroid