如何从DialogFragment获取数据到片段? [英] How to get data from DialogFragment to a Fragment?

查看:306
本文介绍了如何从DialogFragment获取数据到片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想像一下,我有一个 FragmentA ,我从这个开始的对话框格式(框中有 EditText )。如何从 EditText 返回到FragmentA 中的值?我尝试制作像这个,但我没有成功。

Imagine, I have FragmentA from which I startDialogFragment (there are EditText in box). How to can I get back the value from the EditText to FragmentA? I try to make something like this, and this but I was not successful.

推荐答案

在这种情况下, Fragment.onActivityResult()方法很有用。它需要 getTargetRequestCode(),这是您在片段之间设置的代码,以便它们被识别。另外,它需要一个请求代码,通常只要 0 如果代码运行良好,然后一个 Intent 你可以附加一个字符串,像这样

The Fragment.onActivityResult() method is useful in this situation. It takes getTargetRequestCode(), which is a code you set up between fragments so they can be identified. In addition, it takes a request code, normally just 0 if the code worked well, and then an Intent, which you can attach a string too, like so

Intent intent = new Intent();
intent.putExtra("STRING_RESULT", str);

另外, setTargetFragment(Fragment,requestCode)应该用于发送结果的片段中以识别它。总体而言,您将在请求片段中的代码如下所示:

Also, the setTargetFragment(Fragment, requestCode) should be used in the fragment that the result is being sent from to identify it. Overall, you would have code in the requesting fragment that looks like this:

FragmentManager fm = getActivity().getSupportFragmentManager();
DialogFragment dialogFragment = new DialogFragment();
dialogFragment.setTargetFragment(this, REQUEST_CODE);
dialogFragment.show();

发送数据的类(DialogFragment)将使用我们刚才定义的片段来发送数据:

The class to send data (the DialogFragment) would use this Fragment we just defined to send the data:

private void sendResult(int REQUEST_CODE) {
    Intent intent = new Intent();
    intent.putStringExtra(EDIT_TEXT_BUNDLE_KEY, editTextString);
    getTargetFragment().onActivityResult(
        getTargetRequestCode(), REQUEST_CODE, intent);
}

为了接收数据,我们在片段中使用这种类型的类启动DialogFragment:

To receive the data, we use this type of class in the Fragment which initially started the DialogFragment:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Make sure fragment codes match up 
    if (requestCode == DialogFragment.REQUEST_CODE) {
        String editTextString = data.getStringExtra(
            DialogFragment.EDIT_TEXT_BUNDLE_KEY);

此时,您的 EditText 从父片段中的 DialogFragment 。只需在 TextChangeListener()匿名类中使用 sendResult(int)方法,以便在需要时发送文本它。

At this point, you have the string from your EditText from the DialogFragment in the parent fragment. Just use the sendResult(int) method in your TextChangeListener() anonymous class so that the text is sent when you need it.

这篇关于如何从DialogFragment获取数据到片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆