我正在执行的任务是在单击 EditText
后需要显示一个对话框。在该对话框中,我使用 RecyclerView
显示带有 RadioButton
的内容。
现在,我想要做的是,从对话框中选择 RadioButton(RecyclerView 中的内容)后,它应该返回该内容的值,然后对话框应该被关闭。
为了生成对话框,我使用了 DialogFragment
。
由于我是 android 开发的新手,所以我很困惑,无法找到解决方案。
最佳答案
因为你的对话框是一个 DialogFragment
你可以使用两个东西
- If you are starting the dialog from a
Activity
, you can use an interface
创建接口(interface)
public interface ISelectedData { void onSelectedData(String string); }
在您的 Activity 中实现一个接口(interface)
public class MyActivity implements ISelectedData { ..... @Override public void onSelectedData(String myValue) { // Use the returned value } }
在您的对话框中,将界面附加到您的 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"); } }
返回值给Activity时,在你的Dialog中调用即可
mCallback.onSelectedData("myValue");
检查 example在 Android 开发者网站上。
- If you are starting the dialog from a
Fragment
, you can usesetTargetFragment(...)
开始对话
MyDialog dialog = new MyDialog(); dialog.setTargetFragment(this, Constants.DIALOG_REQUEST_CODE); dialog.show(fragmentManager, Constants.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();
获取 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 } } } }
关于android - 从 DialogFragment 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34526866/