How to fix a Bug loading a Fragment inside another Fragment?

1

I have a MainActivity with Navigation Drawer, and all items in this browser open in Fragments. When I start the application I load the homepage as follows:

        android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.ftMainPages, new Fragment01Home());
        ft.commit();

And within that initial page I have another browser with tabs, which also works with fragments inside it.

At startup it loads everything correctly, but when I select a navigation drawer item from the home page, and then return to this page, the tabs become unconfigured. Where only when clicking on the third tab I have the initial page back.

It's a bit complicated to explain with words, but I did a screen recorder, and posted on that link demonstrating the problem: link

Below is my class MainActivity (PagesHome.Class) of the navigation drawer, and the home page class that works with the tabs (Fragment01Home.Class).

PagesHome.Class

public class PagesHome extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private Handler handler = new Handler();
    private static SharedPreferencesUtils SPref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pageshome);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        //Abrir Fragment Inicial (Home)
        android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.ftMainPages, new Fragment01Home());
        ft.commit();
    }

    public void setActionBarTitle(String title) {
        getSupportActionBar().setTitle(title);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        int backstack = getSupportFragmentManager().getBackStackEntryCount();

        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        }  else if (backstack > 0) {
            getSupportFragmentManager().popBackStackImmediate();
        } else {
            ExitDialog();
        }
        //super.onBackPressed();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.pages_home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_search) {
            startActivity(new Intent(getBaseContext(), ActivityPesquisa.class));
            return true;
        } else if (id == R.id.action_settings) {
            startActivity(new Intent(getBaseContext(), ActivityConfiguracoes.class));
            return true;
        } else if (id == R.id.action_exit) {
            ExitDialog();
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        if (id == R.id.nav_home) {
            ft.replace(R.id.ftMainPages, new Fragment01Home());
            ft.commit();
        } else if (id == R.id.nav_favorites) {
            ft.replace(R.id.ftMainPages, new FragmentFavoritos());
            ft.commit();
        } else if (id == R.id.nav_controlpanel) {
            startActivity(new Intent(getBaseContext(), ActivityControlPanel.class));
        } else if (id == R.id.nav_contato) {
            ft.replace(R.id.ftMainPages, new FragmentContato());
            ft.commit();
        } else if (id == R.id.nav_faq) {
            ft.replace(R.id.ftMainPages, new FragmentFAQ());
            ft.commit();
        } else if (id == R.id.nav_sobreita) {
            ft.replace(R.id.ftMainPages, new FragmentSobre());
            ft.commit();
        } else if (id == R.id.nav_privacy) {
            ft.replace(R.id.ftMainPages, new FragmentTerms());
            ft.addToBackStack(null);
            ft.commit();
        } else if (id == R.id.nav_login) {
            LoginDialog();
            return true;
        } else if (id == R.id.nav_deslogar) {
            DeslogarDialog();
            return true;
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


}

Fragment01Home.Class

public class Fragment01Home extends Fragment {

    private static final String TAG = "Fragment01Home";

    private SectionsPageAdapter mSectionsPageAdapter;

    private ViewPager mViewPager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Titulo da página
        ((PagesHome)getActivity()).setActionBarTitle("Teste");
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.nav_view);
        navigationView.setCheckedItem(R.id.nav_home);

        mSectionsPageAdapter = new SectionsPageAdapter(getFragmentManager());

        mViewPager = (ViewPager) view.findViewById(R.id.tabsviewhome);
        setupViewPager(mViewPager);

        TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabshomeitens);
        tabLayout.setupWithViewPager(mViewPager);

        // Inflate the layout for this fragment
       return view;
    }


    private void setupViewPager(ViewPager viewPager) {
        SectionsPageAdapter adapter = new SectionsPageAdapter(getFragmentManager());
        adapter.addFragment(new FragmentNegocios(), "Teste1");
        adapter.addFragment(new FragmentNoticias(), "Teste2");
        adapter.addFragment(new FragmentCompras(), "Teste3");
        adapter.addFragment(new FragmentEventos(), "Teste4");
        adapter.addFragment(new FragmentEmpregos(), "Teste5");
        viewPager.setAdapter(adapter);
    }

    public class SectionsPageAdapter extends FragmentPagerAdapter {

        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }
    }

}

Could someone tell me what I'm doing wrong, and how to solve this problem?

    
asked by anonymous 02.03.2018 / 02:31

1 answer

2

The fragments go up as Bean, to avoid creating a new instance you can do this, it should help in memory control. Insert inside the fragment

@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(false);
    }

Now the possible solution to your bug should be here

mSectionsPageAdapter = new SectionsPageAdapter(getChildFragmentManager());

You must call getChildFragmentManager() so that the viewpager adapter manages the new fragments, so when the parent fragment is removed or deleted from memory, the other fragments affiliate go together

    
05.03.2018 / 17:59