Search code examples
androidandroid-fragmentsandroid-tabhost

onTabSelected change Fragment


I am trying to change the Fragment onTabSelected.

Because at the moment, if you swipe the transitions work fine. But if you click on the Tab, the Fragments won't switch. The Tab gets highlighted, but the content remains the same.

The issue is with my onTabSelected method. I need a suggestion on how to switch to Fragments onTabSelected.

Unfortunately I cannot extend my MainActivity to FragmentActivity, since I won't be able to use ActionBar in that case (I am required to extend ActionBarActivity).

onTabSelected snippet:

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
  int position = tab.getPosition();

  switch (position) {
    case 0:
        break;
    case 1:
        break;
    case 2:
        break;
  }
}

Part of MainActivity that matters here:

public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {

    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;

    // Tab titles
    private String[] tabs = { "Novice", "Članki", "O Tribuni" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initilization
        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getSupportActionBar();
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS);

        // Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));

        }

        /**
         * on swiping the viewpager make respective tab selected
         * */
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });


    }

Any help / suggestion appreciated.


Solution

  • OK, I figured it out by myself guys. The answer is to notify the viewPager about the TabSelected.

    Use this line of code in your onTabSelected method:

    mViewPager.setCurrentItem(tab.getPosition());
    

    Hope it helps someone else too!