Search code examples
androidandroid-fragmentsandroid-tabhostandroid-tablayout

how to replace fragments on tab?


I have an activity with 2 tabs. What im trying to do is to replace between 2 fragments when each tab is pressesd. I also have 2 fragments: fragmentOne and fragmentTwo.When tab one is pressed i want to show fragmentOne and when tab two is pressed i want to show fragmentTwo. I'm not sure if i should create a container layout in the activity and there add the fragmentOne and fragmentTwo, or maybe there is another other way to do it?

here is my code

    public class InboxActivity extends AppCompatActivity {
private TabLayout tabLayout;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_inbox);

    tabLayout = (TabLayout)findViewById(R.id.tabLayout);

    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            Fragment fragment;
            int position = tab.getPosition();
            //requests = position - 0
            //invitations = position - 1
            switch (position){
                case 0:
                     break;
                case 1:
                    break;
            }
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
}

when case is 0 i want to show fragmentOne

when case i 1 i want to show fragmentTwo

How should i do that?


Solution

  • You can do it as follow:

    public void onTabSelected(TabLayout.Tab tab) {
        Fragment fragment = null;
    
        switch (tab.getPosition()) {
            case 0:
            fragment = new FirstFragment();
            break;
    
            case 1:
            fragment = new SecondFragment();
            break;      
        }
    
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.simpleFrameLayout, fragment);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        ft.commit();
    }
    

    Here is a tutorial for more information