Robust way to pass value back from Dialog to Activity on Android?

后端 未结 3 459
北荒
北荒 2020-12-28 11:03

This question has come up several times and I\'ve read all the answers, but I haven\'t seen a truly robust way to handle this. In my solution, I am using listeners from the

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-28 11:14

    You are on the right track, I follow the method recommended by the Android Developers - Using DialogFragments article.

    You create your DialogFragment and define an interface that the Activity will implement, like you have done above with this:

    public interface MyDialogFragmentListener {
        public void onReturnValue(String foo);
    }
    

    Then in the DialogFragment when you want to return the result to the Activity you cast the activity to the interface:

    @Override
    public void onClick(DialogInterface dialog, int id) {
        MyDialogFragmentListener activity = (MyDialogFragmentListener) getActivity();
        activity.onReturnValue("some value");
    }
    

    Then in the Activity you implement that interface and grab the value:

    public class MyActivity implements MyDialogFragmentListener {
        ...
        @Override
        public void onReturnValue(String foo) {
            Log.i("onReturnValue", "Got value " + foo + " back from Dialog!");
        }
    }
    

提交回复
热议问题