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

后端 未结 3 436
北荒
北荒 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!");
        }
    }
    
    0 讨论(0)
  • Very old post but...

    I had appropriate variables in the dialog class:

    int selectedFooStatus = 0; 
    

    Manipulated them when the dialog was interacted with:

    .setSingleChoiceItems(FOO_CHOICES, -1, new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialog, int which) {
    
                           selectedFooStatus = which; 
    
                       }})
    

    In the onclick call back method I cast the returning fragment appropriately and used a getter to return the value.

        public void onDialogPositiveClick(DialogFragment dialog) {
    
                    ChangeFooStatusDialog returnedDialog = (ChangeFooStatusDialog) dialog;
    
                    this.fooStatus = returnedDialog.getSelectedFooStatus();
    
    }
    
    0 讨论(0)
  • 2020-12-28 11:28

    You can fire off an Intent from your Dialog's onClickListner which the Activity will be listening for.

    Take a look at this tutorial on Broadcasting and Receiving Intents

    0 讨论(0)
提交回复
热议问题