我有一个名为“Main”的活动,其中包含三个片段,其中包含tab 1,tab2,tab3。当tab1可见且app进入后台然后恢复时,tab2将显示给我而不是tab1。我该如何解决这个问题。我已经进行了代码检查
代码: -
@Override
protected void onResume() {
super.onResume();
Log.e(TAG, "onResume called::");
if (viewPagerCurrentPosition!=0){
viewPager.setCurrentItem(viewPagerCurrentPosition);
}
if (cCustomAlertAdDialog.isShowing()) {
cCustomAlertAdDialog.dismiss();
}
cCustomAlertAdDialog = new CCustomAlertAdDialog(HomeScreenActivity.this);
// set tabs and fragments in view pager
setTabAndViewPager();
/*Reward code*/
initDrawer();
}
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("viewpagerCurrentPosition",viewPager.getCurrentItem());
Log.e(TAG,"Current position of tab::"+viewPager.getCurrentItem());
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
viewPagerCurrentPosition = savedInstanceState.getInt("viewpagerCurrentPosition");
Log.e(TAG,"Saved position of tab::"+viewPagerCurrentPosition);
}
并在onRestart
我使用了这行代码: -
if (viewPagerCurrentPosition!=0){
viewPager.setCurrentItem(viewPagerCurrentPosition);
}
以上代码在我的方案中不起作用
答案 0 :(得分:0)
这是每次加载的默认选项卡。 试试这个 : 在onCreate和onResume
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewPager.setCurrentItem(1);
}
@Override
protected void onResume() {
super.onResume();
viewPager.setCurrentItem(1);
}
如果有帮助请告诉我