Return values from DialogFragment

梦想的初衷 提交于 2019-11-29 11:49:14

Because your dialog is a DialogFragment you can use two things

  1. If you are starting the dialog from a Activity, you can use an interface
  • create an interface

    public interface ISelectedData {
        void onSelectedData(String string);
    }
    
  • implement an interface in your Activity

    public class MyActivity implements ISelectedData {
    
        .....
    
        @Override 
        public void onSelectedData(String myValue) {
            // Use the returned value
        }
    }
    
  • in your Dialog, attach the interface to your Activity

    private ISelectedData mCallback;
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    
        try {
            mCallback = (ISelectedData) activity;
        }
        catch (ClassCastException e) {
            Log.d("MyDialog", "Activity doesn't implement the ISelectedData interface");
        }
    }
    
  • when returning the value to Activity, just call in your Dialog

    mCallback.onSelectedData("myValue");
    

    Check the example on the Android developer site.

  1. If you are starting the dialog from a Fragment, you can use setTargetFragment(...)
  • starting the Dialog

    MyDialog dialog = new MyDialog();
    dialog.setTargetFragment(this, Constants.DIALOG_REQUEST_CODE);
    dialog.show(fragmentManager, Constants.DIALOG);
    
  • returning the value from the Dialog

    Bundle bundle = new Bundle();
    bundle.putString(Constants.MY_VALUE, "MyValue");
    
    Intent intent = new Intent().putExtras(bundle);
    
    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);
    
    dismiss();
    
  • getting the value in Fragment

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == Constants.DIALOG_REQUEST_CODE) {
    
            if (resultCode == Activity.RESULT_OK) {
    
                if (data.getExtras().containsKey(Constants.MY_VALUE)) {
    
                    String myValue = data.getExtras().getString(Constants.MY_VALUE);
    
                    // Use the returned value
                }
            }
        }
    }     
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!