Return values from DialogFragment

北战南征 提交于 2019-12-18 07:00:05

问题


I am doing task in which I need to show a dialog after clicking on EditText. In that dialog I show contents with RadioButtons using RecyclerView.

Now, what I want to do is, after selecting RadioButton (content which is in the RecyclerView) from dialog, it should return value of that content and then dialog should be dismissed.

To generate a dialog I've used a DialogFragment.

As I'm new in android development, I am totally confused and unable to find the solution.


回答1:


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
                }
            }
        }
    }     
    


来源:https://stackoverflow.com/questions/34526866/return-values-from-dialogfragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!