Overlapping Fragments when resuming Activity

2019-04-15 21:20发布

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: enter image description here

1条回答
Luminary・发光体
2楼-- · 2019-04-15 22:04

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.

查看更多
登录 后发表回答