Android FragmentActivity如何向Fragments传递变量?
我有一个运行完美的 FragmentActivity,在(相同的)Fragments 之间具有平滑的水平滑动。我现在想知道如何将变量发送到 Fragment 对象?
我的代码如下所示:
private void initialisePaging() {
fragments = new Vector<Fragment>();
for (int i = 0; i < wiList.length; i++) {
WhiteboardImage tmpWi = wiList[i];
intent.putExtra("displayNow", tmpWi.getFilename());
fragments.add(Fragment.instantiate(this, GalleryFragment.class.getName()));
}
this.mPagerAdapter = new GalleryPagerAdapter(super.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager) super.findViewById(R.id.viewpager);
pager.setAdapter(this.mPagerAdapter);
// Define which item of the list will be displayed
pager.setCurrentItem(4);
}
所以基本上在 for() 循环中,我多次将 GalleryFragment 对象添加到 PagerAdapter 中。我现在想做的是每个 GalleryFragment 都有一个不同的 ID(或字符串)。我无法弄清楚如何将不同的值传递给该循环中的每个 GalleryFragment 对象。此时每个对象都获得完全相同的值。
感谢您的任何帮助。
I have a perfectly fine running FragmentActivity with a smooth horizontal sliding between the (identical) Fragments. I was wondering now how I can send a variable to the Fragment objects?
My code looks like this:
private void initialisePaging() {
fragments = new Vector<Fragment>();
for (int i = 0; i < wiList.length; i++) {
WhiteboardImage tmpWi = wiList[i];
intent.putExtra("displayNow", tmpWi.getFilename());
fragments.add(Fragment.instantiate(this, GalleryFragment.class.getName()));
}
this.mPagerAdapter = new GalleryPagerAdapter(super.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager) super.findViewById(R.id.viewpager);
pager.setAdapter(this.mPagerAdapter);
// Define which item of the list will be displayed
pager.setCurrentItem(4);
}
So basically in the for() loop I am adding multiple times the GalleryFragment object to the PagerAdapter. What I now want to do is that each GalleryFragment gets a different ID (or string for that matter). I could not figure out how to pass a different value to each GalleryFragment object within that loop. At the moment each object gets the very same value.
Thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我通常是这样做的:
如果数据从一开始就可用并且没有改变,那么我将它们解析为fragment.instantiate的参数。然后在此函数中,您可以将它们作为带有 .putArguments(...) 的捆绑包放入您的片段中。在片段的 onCreate 中,您可以使用 .getArguments(...) 检索数据
I usually made it like this:
If the data are available from beginning and not change then I parsed them as parameters of fragment.instantiate. then in this function you can put them as a Bundle with .putArguments(...) to your fragment. And in your fragment's onCreate you can retrieve the data with .getArguments(...)