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

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

问题描述

想象一下,我的碎裂的从我(在盒子有的EditText )的 startDialogFragment 的。如何我能回到从的EditText 来的碎裂的价值?我尽量让类似和<一href="http://stackoverflow.com/questions/13733304/callback-to-a-fragment-from-a-dialogfragment">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()方法是在这种情况下是有用的。它采用 getTargetRequest code(),这是一个code设置了片段之间,使他们能够被识别。此外,它需要一个请求code,通常只是 0 如果code运作良好,那么意图,你可以将一个字符串太,像这样

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(片段,请求code)该结果是从发送应在片段被用来识别它。总之,你将有code在请求片段是这样的:

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 。只需使用 sendResult(INT)方法,在你的 TextChangeListener()匿名类,这样,当你需要的文本发送吧。

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天全站免登陆