Android God
Android God

Reputation: 79

How to replace a fragment from the main activity

I have a two fragments, mainactivity initially have fragment called "Dashboard fragment" Upon clicking this a button I have to replace this fragment by new fragment called "Dashboard1 fragment" but problem is Dashboard fragment is not hide/remove and now it showing both

My code

        public void onClick(View view) {
            Fragment fragment = null;
            fragment = new Dash_Section();
            replaceFragment(fragment);

        }
     public void replaceFragment(Fragment someFragment) {
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.frame_container, someFragment);
    transaction.addToBackStack(null);
    transaction.commit();

How can I remove or replace the Dashboard fragment? Any help will be appreciated.

Upvotes: 0

Views: 1374

Answers (1)

TIMBLOCKER
TIMBLOCKER

Reputation: 438

First of all, you have to declare a FragmentContainer in you Layout file of the MainActivity. This is the space where both fragments will be shown. Then you can instantiate both Fragments and change between them by adding:

 Dashboard1Fragment dFragment = new Dashboard1Fragment();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, dFragment);
            fragmentTransaction.commit();

This will replace the content of your FragmentContainer and instantiate a new Fragment, without overlapping both Fragments.

Upvotes: 1

Related Questions