我正在开发一个Android应用程序,它有四个片段和tablayout,每个片段都有连接错误对话框。
我从互联网上搜索了这个问题,但我没有得到我的问题答案。 请有人帮帮我。谢谢... 抱歉我的英语不好
这是代码
viewPager = (ViewPager) findViewById(R.id.viewpagerMain);
tabLayout = (TabLayout) findViewById(R.id.tablayoutMain);
tabLayout.addTab(tabLayout.newTab().setText("Noticeboard"));
tabLayout.addTab(tabLayout.newTab().setText("News"));
tabLayout.addTab(tabLayout.newTab().setText("Events"));
tabLayout.addTab(tabLayout.newTab().setText("Result"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager(), tabLayout.getTabCount()));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setOffscreenPageLimit(0);
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) {
}
});
这是MyAdapter类
class MyAdapter extends FragmentStatePagerAdapter {
int num_of_tab;
public MyAdapter(FragmentManager fm, int num_of_tab) {
super(fm);
this.num_of_tab = num_of_tab;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
NoticeBoardFragment noticeBoardFragment = new NoticeBoardFragment();
return noticeBoardFragment;
case 1:
NewsFragment newsFragment = new NewsFragment();
return newsFragment;
case 2:
EventsFragment eventsFragment = new EventsFragment();
return eventsFragment;
case 3:
ResultFragment resultFragment = new ResultFragment();
return resultFragment;
default:
return null;
}
}
@Override
public int getCount() {
return num_of_tab;
}
}
答案 0 :(得分:0)
覆盖每个片段中的setUserVisibleHint,并在if(isVisibleToUser)而不是Oncreate中编写对话框代码。这应该可以解决你的问题
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser) {
//dialog box code here
}
}