Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android TabLayout (API 22) add fragment to each tab without ViewPager

I'm trying out Android's new TabLayout class to add two tabs just below my ActionBar. Each tab will host a different fragment.

Also, I don't want to be able to swipe between my two tabs - to navigate between my tabs, I'd like to be able to ONLY touch the tab I want to navigate to.

Inside my MainActivity, I have:

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Newsfeed"));
    tabLayout.addTab(tabLayout.newTab().setText("Random"));

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            // IDEALLY HERE, I'd like to do something like
            // tab.setFragment(new MainFragment()).
        }

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

        }

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

        }
    });
 }

So i'd like to override my onTabSelected and onTabReselected methods so that toggling between the two tabs leads to displaying two different fragments respectively. There's not much I could find online about the new TabLayout independent of the ViewPager.

ANy clues? Thanks!

like image 647
user2635088 Avatar asked Feb 10 '23 19:02

user2635088


1 Answers

@Override
public void onTabSelected(TabLayout.Tab tab) {
  Fragment f=heyWhatFragmentGoesInThisTab(tab);

  getFragmentManager()
    .beginTransaction().replace(R.id.where_the_tab_contents_go, f).commit();
}

where you need to write:

  • heyWhatFragmentGoesInThisTab() to return the Fragment that should be shown based upon the selected tab, and

  • R.id.where_the_tab_contents_go, which is a FrameLayout that serves as the container for the active fragment

IOW, you change fragments in response to the TabLayout the same way as you change fragments in response to action bar item clicks, nav drawer item clicks, or any other GUI event.

like image 81
CommonsWare Avatar answered Feb 12 '23 10:02

CommonsWare