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!
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With