如何从DialogFragment数据到一个片段?片段、数据、DialogFragment

2023-09-05 06:57:25 作者:任凭寂寞沸腾

想象一下,我的碎裂的从我(在盒子有的EditText )的 startDialogFragment 的。如何我能回到从的EditText 来的碎裂的价值?我尽量让类似这和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.