Overlapping Fragments when resuming Activity

无人久伴 提交于 2019-12-06 09:22:09

问题


I have a problem with my android app, I'm developing with Android STUDIO IDE. Pretty much when I leave the app in the background for a few minutes, or is killed by the system or I mix the different layouts of the fragment. I have put a picture below:

I've already tried a variety of methods, if you have others write as well. Thank you in advance.

super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ViewPager pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));

        actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        ActionBar.TabListener tl = new ActionBar.TabListener() {
            @Override
            public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {

            }

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

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

            }
        };

        String label1 = getResources().getString(R.string.label1);
        ActionBar.Tab tab;
        tab = actionBar.newTab();
        tab.setText(label1);

        tab.setIcon(R.drawable.download);


        //tab.setIcon(R.drawable.data);
        tab.setTabListener(tl);
        actionBar.addTab(tab);

        String label2 = getResources().getString(R.string.label2);
        tab = actionBar.newTab();
        tab.setText(label2);
        tab.setIcon(R.drawable.search);


        tab.setTabListener(tl);
        actionBar.addTab(tab);

        String label3 = getResources().getString(R.string.label3);
        tab = actionBar.newTab();
        tab.setText(label3);
        tab.setIcon(R.drawable.television);

        tab.setTabListener(tl);
        actionBar.addTab(tab);

Image:


回答1:


So the problem is that you have fragment A added in your onCreate. After navigating to fragment B your activity goes into the background. In certain cases as you know android can kill your background activity and force it to recreate itself when it comes to the foreground. Thus your activity recreates itself with fragment B which was its last state when it went into the background, as well as adds fragment A because onCreate was called. You can solve this by doing a savedinstancestate check in your onCreate.



来源:https://stackoverflow.com/questions/18590582/overlapping-fragments-when-resuming-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!