我試圖從Map
片段訪問myfunction()
片段Tabs
中的位置。從子片段訪問父片段方法
我試過以下行Tabs parentFragment = (Tabs) getParentFragment();
但是parentFragment爲null。
我閱讀了有關這個主題的所有主題,但沒有人幫助我......(也許我誤解了他們之後)。
我有以下文件:
片段從中我要調用父類的方法。
public class Map extends Fragment {
View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.map_fragment, container, false);
Tabs parentFragment = (Tabs) getParentFragment();
parentFragment.myfunction();
// it crash because parentFragment is null...
return rootView;
}
}
家長片段含有myFunction的()方法。
public class Tabs extends Fragment {
private View rootview;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
rootview = inflater.inflate(R.layout.tabs, container, false);
TabLayout tabLayout = (TabLayout) rootview.findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) rootview.findViewById(R.id.pager);
Context context = (HomeContainer)getContext();
final TabsAdapter adapter = new TabsAdapter
(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(3);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return rootview;
}
// the function I desire to call
public void myfunction(){
}
}
的TabsAdapter
(因爲Map
片段是選項卡)。
public class TabsAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public TabsAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Map tab1 = new Map();
return tab1;
case 1:
Settings tab2 = new Settings();
return tab2;
case 2:
Others tab3 = new Others();
return tab3;
default:
return null;
}
}
@Override
public int getCount() {
return mNumOfTabs;
}
}
我相對較新的Android,所以我有點失落! 在此先感謝您的幫助。
我剛剛嘗試過,仍然是同樣的錯誤... – Bobo159951
也用getChildFragmentManager替換getSupportFragmentManager。這是這裏的主要問題。 – natario
你是我的英雄!非常感謝! – Bobo159951