从DialogFragment返回值 [英] Return values from DialogFragment
问题描述
我正在执行的任务是单击EditText
后需要显示一个对话框.在该对话框中,我使用RecyclerView
显示具有RadioButton
的内容.
I am doing task in which I need to show a dialog after clicking on EditText
. In that dialog I show contents with RadioButton
s using RecyclerView
.
现在,我要做的是,从对话框中选择RadioButton(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.
要生成对话框,我使用了DialogFragment
.
To generate a dialog I've used a DialogFragment
.
由于我是android开发的新手,所以我很困惑,无法找到解决方案.
As I'm new in android development, I am totally confused and unable to find the solution.
推荐答案
由于您的对话框是DialogFragment
,因此您可以使用两件事
Because your dialog is a DialogFragment
you can use two things
- 如果要从
Activity
启动对话框,则可以使用界面
- 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");
在Android开发者网站上查看示例.
Check the example on the Android developer site.
- 如果要从
Fragment
启动对话框,则可以使用setTargetFragment(...)
- 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 } } } }
这篇关于从DialogFragment返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 如果要从