我试图从Map
片段访问父级片段myfunction()
中的Tabs
。
我尝试了以下行Tabs parentFragment = (Tabs) getParentFragment();
,但parentFragment为null。
我阅读了有关这个主题的所有主题,但没有一个能帮助我......(也许我误解了它们之后)。
我有以下文件:
我想从中调用Parent方法的片段。
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()方法的Parent Fragment。
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比较新,所以我有点迷失了! 在此先感谢您的帮助。
答案 0 :(得分:2)
apt-get remove --purge virtualbox-ose-guest-dkms virtualbox-ose-guest-utils virtualbox-ose-guest-x11 && apt-get autoremove && apt-get autoclean
可能为时过早,在最糟糕的情况下尝试onCreateView
或onViewCreated
。
答案 1 :(得分:0)
我建议你在onCreateView之后放置并检查实例。
Fragment parentFragment = getParentFragment();
if(parentFragment instanceof Tab) {
((Tab) parentFragment).myfunction();
}