问题
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
- 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.
- If you are starting the dialog from a
Fragment, you can usesetTargetFragment(...)
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