将数据从一个片段传递到另一个片段

将数据从一个片段传递到另一个片段

问题描述:

我有一个包含两个片段的 Activity,我需要将一个字符串从 FragmentA 传递到 FragmentB.

I have an Activity with two fragments and I need to pass a string from FragmentA to FragmentB.

为了传递数据,我在 FragmentA 中有这个:

To pass the data, I have this in my FragmentA:

    Intent intent = new Intent(getActivity(), FragmentB.class);
    intent.putExtra("name", "Mark");
    startActivity(intent);

为了获取数据,我在 FragmentB 中做了这个

And to get the data, I did this in FragmentB

    Intent intent = getActivity().getIntent();
    Bundle b = intent.getExtras();

    if(b!=null)
    {
        String name =(String) b.get("name");
        nameTextView.setText(name);
    }

但这行不通.有没有一种特定的方法可以将字符串从一个片段传递到另一个片段?

But this is not working. Is there a specific way to pass a string from one fragment to another fragment?

  1. 如果片段由相同的活动托管-您不能将意图投射到 Fragment.Fragment 是 Activity 的一部分,它本身并不是一个 Activity.因此,要在片段之间共享字符串,您可以在 Activity 中声明一个静态字符串.从片段 A 访问该字符串以设置值并在片段 B 中获取字符串值.
  2. 两个片段都由不同的活动托管-然后你可以使用 putExtra 将一个字符串从 Activity A 的 Fragment A 传递给 Activity B.将该字符串存储在 Activity B 中并在 Fragment B 中使用它.