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

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

问题描述

想象一下,我有FragmentA,我从它startDialogFragment(框中有EditText).如何将 EditText 中的值取回 FragmentA?我尝试制作类似 this这个 但我没有成功.

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)将使用我们刚刚定义的这个 Fragment 来发送数据:

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的Fragment中使用了这种类型的类:

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);

此时,您拥有来自父片段中 DialogFragmentEditText 的字符串.只需在您的 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 获取数据到 Fragment?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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