4

アプリケーションのいくつかのポイントで表示する必要があるカスタム AlertDialog で DialogFragment を作成しました。このダイアログは、ユーザーにデータの入力を求めます。

ダイアログが呼び出されてユーザーの入力を待機し、ユーザーがOKボタンを押したときに変数アクションを実行するアクティビティを作成する方法を見つけたいと思います(キャンセルを押した場合は何もしません)。

私の知る限り、Androidには「モーダルダイアログ」がないので、この(かなり普通の)種類の動作を実現する適切な方法は何でしょうか?

4

1 に答える 1

7

Fragment がその Activity と通信できるようにするには、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
    }
}
于 2013-06-02T14:25:49.837 に答える