![](/img/trans.png)
[英]How to get elements of fragments created by ViewPager in MainActivity?
[英]Unable to pass data from MainActivity to ViewPager Fragments
在我的Android程序中,我将三个Fragments
包装在ViewPager
。 我有一个ArrayList<MyObject>
,它填充在MainActivity
的onResume()
方法内。 如何将ArrayList<MyObject>
从MainActivity
发送到子Fragments
? 我想要的是每当应用程序出现在前台时,使用ArrayList<MyObject>
更新片段。 对于这个特定的问题有很多解决方案,但是没有一个对我有用。 我已经尝试使用Bundles
将参数传递给Fragments
。 为了进行测试,我试图将简单的int值传递给子片段:在MainActivity
的onCreate()
中:
Bundle bundle = new Bundle();
bundle.putInt("INTEGER",2);
在MainActivity
的onResume()
中:
Fragment frag = MyFragPageAdapter.getItem(1);
frag.setArguments(bundle);
在我的Fragment
的onCreate()
方法中:
final Bundle args = getArguments();
final int myInt = args.getInt("INTEGER");
Log.v("IN FOREGROUND", myInt+"");
谁能帮帮我吗? 提前致谢!
适配器:
public class MyFragPageAdapter extends FragmentPagerAdapter implements IconTabProvider {
private final int[] ICONS = { R.drawable.ic_action_cc_bcc, R.drawable.ic_action_call,
R.drawable.ic_action_chat};
private final String[] tabTitles = {"Contacts", "Calls", "Messages" };
public FragmentPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int arg0) {
switch (arg0) {
case 0:
return new ContactList();
case 1:
return new DialPad();
case 2:
return new BlockedList();
default:
break;
}
return null;
}
@Override
public int getCount() {
return 3;
}
@Override
public int getPageIconResId(int position) {
// TODO Auto-generated method stub
return ICONS[position];
}
/* (non-Javadoc)
* @see android.support.v4.view.PagerAdapter#getPageTitle(int)
*/
@Override
public CharSequence getPageTitle(int position) {
// TODO Auto-generated method stub
return tabTitles[position];
}
在ContactList的构造函数内部,尝试进行辩论并检查。
Bundle bundle = new Bundle();
bundle.putInt("INTEGER",2);
Fragment frag = MyFragPageAdapter.getItem(1);
frag.setArguments(bundle);
首先使您的arraylist对象“可序列化”
比
在片段A中
String TabOfFragmentB = ((AndroidViewPagerActivity)getActivity()).getTabFragmentB();
MyFragmentB fragmentB = (MyFragmentB)getActivity()
.getSupportFragmentManager()
.findFragmentByTag(TabOfFragmentB);
fragmentB.sendData(yourArraylist<Object>);
在片段B中
全球宣言
private void myResultedData= null;
在onCreateView之外
public yourArraylist<Object> sendData(yourArraylist<Object> t){
myResultedData = t;
}
在onCreateView中使用“ myResultedData”
有关更多详细信息,并了解视图寻呼机片段之间的通信概念,请参阅链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.