片段重新初始化初始选项卡选项上的内容 - ANDROID

时间:2015-08-04 10:09:08

标签: android android-fragments tabs android-viewpager fragment-tab-host

我有一个使用ViewPager的应用程序,它充当TabHost。问题是,当应用程序启动时,所有显示都很好,在所有3个选项卡之间滑动。

但是,在重新选择第一个选项卡时,应用程序将重新初始化但不显示正确的内容,应用程序应保留Fragments当前状态而不是重新初始化。

代码:

  

TabAdapter.java

public class TabAdapter extends FragmentPagerAdapter{


public TabAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {

    switch(position){
        case 0:
            return new MapFragmentView();
        case 1:
            return new LogView();
        case 2:
            return new SettingsView();
    }

    return null;
}

@Override
public int getCount() {
    return 3;
}

}

  

MapsActivity.java(主要活动)

public class MapsActivity extends FragmentActivity implements ActionBar.TabListener {

private ViewPager viewPage;
private TabAdapter myAdapter;
private ActionBar actionBar;
public static FragmentManager fragmentManager;

private String[] tabNames = {"Map", "Log" , "Settings"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    fragmentManager = getFragmentManager();

    viewPage = (ViewPager) findViewById(R.id.pager);
    actionBar = getActionBar();
    myAdapter = new TabAdapter(getSupportFragmentManager());

    viewPage.setAdapter(myAdapter);
    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Adding Tabs
    for (String tab_name : tabNames) {
        actionBar.addTab(actionBar.newTab().setText(tab_name)
                .setTabListener(this));
    }

    viewPage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            // on changing the page
            // make respected tab selected
            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });

}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
    viewPage.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {

}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
    viewPage.setCurrentItem(tab.getPosition());
}
}

初步观点:

Initial View of Tab

重新选择地图标签后的实际结果:

Upon Reselecting Maps Tab

预期结果:

What should actually happen

据我所知,在TabAdapter文件中,每次调用getPosition时我们都会创建新实例,因此可能会出现问题。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:6)

您可以尝试设置PageViewer

的方法setOffscreenPageLimit()
viewPage.setOffscreenPageLimit(3);