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

5
我可以帮您进行翻译。该内容是关于it技术的,涉及到Activity和两个Fragment之间传递字符串的问题。
为了传递数据,您可以在FragmentA中添加以下代码:
    Intent intent = new Intent(getActivity(), FragmentB.class);
    intent.putExtra("name", "Mark");
    startActivity(intent);

为了获取数据,我在FragmentB中进行了以下操作

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

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

但这并不起作用。有没有一种特定的方法可以将一个字符串从一个片段传递到另一个片段?
4个回答

15
  1. 如果片段由同一个活动托管- 您不能将Intent转换为Fragment。 Fragment作为Activity的一部分,它本身不是一个活动。因此,要在片段之间共享字符串,您可以在Activity中声明静态字符串。从片段A访问该字符串以设置其值,并在片段B中获取字符串值。
  2. 如果两个片段由不同的活动托管- 然后,您可以使用putExtra将来自Activity A的Fragment A中的字符串传递到Activity B。 在Activity B中存储该字符串并在Fragment B中使用它。

4

要在Fragment之间传递数据,您可以使用setArguments(Bundle b)。例如:

public class FragmentA extends Fragment {

  public static FragmentA newInstance(String name) {
    Bundle bundle = new Bundle();
    bundle.putString("name", name);
    FragmentA f = new FragmentA(); 
    f.setArguments(bundle);
    return f;
  }

}

3
您可以像下面这样做:
 Fragment fr=new friendfragment();
 FragmentManager fm=getFragmentManager();
 android.app.FragmentTransaction ft=fm.beginTransaction();
 Bundle args = new Bundle();
 args.putString("CID", "your value");
 fr.setArguments(args);
 ft.replace(R.id.content_frame, fr);
 ft.commit(); 

要接收数据,请按照以下步骤进行:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("CID");    
    return inflater.inflate(R.layout.fragment, container, false);
}

0

在 FragmentActivity 1 的片段 A 中的代码:

fb 是我创建的 bean 的实例,ID 是参数。

Intent intent = new Intent(getContext(), FragmentActivity2.class);
        intent.putExtra("id", fb.ID);
startActivity(intent);

在 FragmentActivity 中编写代码,用于 2 个 fragment 的任何操作:

fragmentA= (FragmentActivity2) getActivity();
String cust_id = fragmentA.getIntent().getExtras().getString("id");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接