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

I am testing a new TabLayout class to add two tabs just below my ActionBar. Each tab will have a different fragment.

Also, I don't want to be able to scroll between two tabs - to move between my tabs, I would like to be able to ONLY touch the tab that I want to go 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 would like to redefine my onTabSelected and onTabReselected methods, so switching between two tabs leads to displaying two different fragments respectively. There are not many that I could find on the Internet about the new TabLayout regardless of the ViewPager.

ANY clues? Thank!

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

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

:

  • heyWhatFragmentGoesInThisTab(), Fragment, ,

  • R.id.where_the_tab_contents_go, FrameLayout,

IOW, TabLayout , , GUI.

+7

All Articles