[英]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);
}
但這不起作用。 是否有特定的方法將字符串從一個片段傳遞到另一個片段?
要在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.