I have a tab layout with 3 tab items each having its own fragment to load at runtime when selected.
MainActivity.class: Here call to LoadFragment according to position of selected tab.
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
LoadFragment(new LocationFragment());
break;
case 1:
LoadFragment(new InformationFragment());
break;
case 2:
LoadFragment(new CommentsFragment());
break;
}
}
My question is how can I use switch statement for the logic to load proper fragment using fragment manager? I don't want to have if else statement hierarchy.
private void LoadFragment(Fragment fragment) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
switch (*some logic here*) {
case fragment instanceof LocationFragment:
Log.i("MainActivity", "inside load fragment");
ft.replace(R.id.coordinate_layout, new LocationFragment());
break;
case fragment instanceof InformationFragment:
ft.replace(R.id.coordinate_layout, new InformationFragment());
break;
case fragment instanceof CommentsFragment:
ft.replace(R.id.coordinate_layout, new CommentsFragment());
break;
ft.commit();
}
}