如何使用Android中的intent将活动之间的数据传递给片段

前端之家收集整理的这篇文章主要介绍了如何使用Android中的intent将活动之间的数据传递给片段前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我现在可以将值存储在一个变量中,我希望将该变量传递给片段.

使用以下代码,我可以加载片段.

@H_404_7@ public class AndroidListFragmentActivity extends Activity { Fragment2 f2; public static String itemname; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.apetiserfragement); itemname=getIntent().getStringExtra("itemname"); Bundle args=new Bundle(); args.putString("itemname",itemname); f2=new Fragment2(); f2.setArguments(args); } }

(这里我使用XML页面加载片段)itemname

输出分为2个窗口,一个用于扩展listfragment(对于listview).一个用于碎片

Fragment2.xml

@H_404_7@ public class Fragment2 extends Fragment { String itemname; @Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) { // TODO Auto-generated method stub System.out.println(getArguments().getString("itemname")); return inflater.inflate(R.layout.fragment2,container,false); } @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } }

我希望通过Fragment2.class传递此类itemname中的AndroidListFragmentActivity.

最佳答案
使用其中一个fragment constructors中提供的软件包,然后您应该能够通过在onCreateView()中的getArguments()所在位置检索Bundle

例:

@H_404_7@YourFragment.instantiate(context,"fragName",yourBundleWithValue);

然后,在你的片段中:

@H_404_7@public View onCreateView(LayoutInflater inflater,Bundle savedInstanceState) { getArguments().getStringValue("name"); //Returns your string value return inflater.inflate(R.layout.fragment2,false); }

猜你在找的Android相关文章