![](/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.