簡體   English   中英

將數據從一個片段傳遞到另一個片段

[英]Passing data from one fragment to another

我有一個帶有兩個片段的Activity,我需要將一個字符串從FragmentA傳遞給FragmentB。

為了傳遞數據,我在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);
    }

但這不起作用。 是否有特定的方法將字符串從一個片段傳遞到另一個片段?

  1. 如果片段由同一活動托管 - 您無法將意圖轉換為Fragment。 片段作為Activity的一部分,它本身不是一個活動。 因此,要在片段之間共享字符串,可以在Activity中聲明一個靜態字符串。 從片段A訪問該字符串以設置值並在片段B中獲取字符串值。
  2. 兩個片段都由不同的活動托管 - 然后您可以使用putExtra將活動A的片段A中的字符串傳遞給活動B.將該字符串存儲在活動B中並在片段B中使用它。

要在Fragments之間傳遞數據,可以使用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;
  }

}

你可以做類似下面的事情,

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

FragmentActivity 1片段中的代碼A:

fb是我創建的bean的實例,ID是參數

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

FragmentActivity 2片段中的代碼Any:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM