How to fix a Bug with loading a Fragment within another Fragment?

Asked

Viewed 127 times

0

I have a Mainactivity with Navigation Drawer, and all the items in this browser opens in Fragments. When starting the application I load the home page as follows:

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

And inside this home page I have another browser with tabs, which also works with Fragments inside it.

When starting it loads everything correctly, but when I select a Drawer navigation item leaving the home page, and then return to this page, the tabs are not set. Where just by clicking on the third tab I have the home page back.

It gets a little complicated to explain with words, but I did a screen Recorder, and posted on this link demonstrating the problem: https://imgur.com/a/yY0yj

Below is my Mainactivity class (Pageshome.Class) of the navigation Drawer, and the class of the initial page 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?

  • tries to use getSupportFragmentManager() instead of getFragmentManager() and vice versa

  • Thanks for the @Igoroliveira tip, but can you tell me why the change and difference between the two? I’ll give a search tbm. Valew

  • I tested here @Igoroliveira, and it didn’t work. Actually it got even worse. Now he gives the same bugs only with all tabs, even the ones that before did not give.

1 answer

1


The Factions go up as Bean, to avoid being created a new instance you can do this, should help in memory control. Insert into the Fragment

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

Now the possible solution for your bug should be here

mSectionsPageAdapter = new SectionsPageAdapter(getChildFragmentManager());

You must call getChildFragmentManager() for the viewpager Adapter to manage the new fragments, so when the parent fragment is removed or deleted from memory, the other affiliated fragments go together

  • Perfect. It worked perfectly, thank you very much, helped d+++

  • You’re welcome, good luck with the project

  • Thank you, for you In your hugs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.