How to change tab when sliding on the screen?

Asked

Viewed 1,948 times

1

I have an Activity that has 2 tabs and wanted to know how to change tab not only when clicking on one of them, but also when sliding (left and right) on the screen.

My Activity:

public class MainActivity extends Activity {
    private Fragment1 frag1;
    private Fragment2 frag2;
    ActionBar bar;
    Tab tab1;
    Tab tab1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bar = getActionBar();
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        frag1 = new Fragment1();
        frag2 = new Fragment2();

        tab1 = bar.newTab();
        tab1.setText("Tab1");
        tab1.setTabListener(new ConfigTab(frag1, R.id.frag1));
        bar.addTab(tab1);

        tab2 = bar.newTab();
        tab2.setText("Tab2");
        tab2.setTabListener(new ConfigTab(frag2, R.id.frag1));
        bar.addTab(tab2);

    }
}

And the configTab class:

public class ConfigTab implements TabListener {
    private Fragment fragment;
    private int placeholder;

    public ConfigTab(Fragment fragment, int placeholder) {
        this.fragment = fragment;
        this.placeholder = placeholder;
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        ft.add(placeholder, fragment);
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        ft.remove(fragment);
    }
}

Error print on mainActivity, highlighted below:

inserir a descrição da imagem aqui

Print of the error occurred:

inserir a descrição da imagem aqui

  • It’s a little long to answer your question without knowing your code. There is some work behind what you ask and that work in the form of an answer may not meet your particular case. It would be better to put the relevant code in the question to get a more targeted help to your particular case.

  • @Zuul ready posted.. the tabs then working perfectly when clicked... just wanted when sliding on the screen automatically change the tabs.

  • I added a photo in my post of the line where the error occurs...

1 answer

4


When I implemented this, I did it like this. In the Activity layout, I put it like this:

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</android.support.v4.view.ViewPager>

So the only View element in my Activity is Viewpager. To initialize Viewpager, in the onCreate method:

ViewPager viewPager = (ViewPager) findViewById(R.id.pager);

For this viewPager assigns an Adapter, in the case a class I called Tabspagera pter:

package br.com.exemplo.application.adapters;

import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v13.app.FragmentPagerAdapter;
import br.com.exemplo.presentation.views.fragments.PrimeiroFragment;
import br.com.exemplo.presentation.views.fragments.SegundoFragment;

public class TabsPagerAdapter extends FragmentPagerAdapter {
public PrimeiroFragment primeiroFragment;
public SegundoFragment segundoFragment;


public TabsPagerAdapter(FragmentManager fm) {
    super(fm);
    primeiroFragment = new PrimeiroFragment();
    segundoFragment = new SegundoFragment();
}

@Override
public Fragment getItem(int index) {

    switch (index) {
    case 0:
        // Seu primeiro fragment
        return primeiroFragment;
    case 1:
        // Seu segundo fragment
        return segundoFragment;
    default:
        return null;
    }

}

@Override
public int getCount() {
    // get item count - quantidade de tabs
    return 2;
}

}

Back to Activity, assign Adapter to viewPager, create objects Tab and attribute these to ActionBar:

viewPager.setAdapter(mAdapter);
ActionBar actionBar = getActionBar();
String[] tabs = {"Lista Publicações", "Nova Publicação"};
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);        
// Adicione aqui as tabs:
for (String tab_name : tabs) {
    actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));

}

And also add a OnPageChangeListener to your viewPager:

        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) {
        }
    });

Well, now I believe that with viewPager it works. This OnPageChangeListener may be useful to you, but is not mandatory. For TabListeners implemented the interface ActionBar.TabListener on my Activity:

...
public class MainActivity extends Activity implements ActionBar.TabListener{
...

And with that are created the methods you use in ConfigTab in Activity. (If you prefer, assign Configtab as Tablistener for each Tab object and do not implement the Actionbar interface.Tablistener):

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    // on tab selected
    // show respected fragment view
    viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
  • this your code makes the "slide" on the android screen to left and right change tabs?

  • Yes, it will work either by clicking on tabs or by sliding with your finger. Sorry, I missed explaining that method onPageScrolled is called whenever you slide between tabs.

  • hum ok... I will try to implement here.. + 1 in your reply.. after I implement I mark as answered thank you

  • To do this you need to create the Tab type objects and assign to each Tablistener but the way you did tab = bar.newTab() and bar.addTab(tab) would not work in this case. I believe that the TabListeners are not necessary due to the use of PageChangeListener which implements three different methods to detect Tabs change which may be sufficient for your case.

  • this line is not certain mAdapter.listPublicationsFragment.refreshListPublications();

  • I put it by mistake, you can remove it

  • needs instance mdapter? if yes it needs a fragmentmanager how to do? because mAdapter = new Tabspagera pter(getFragmentManager()); error

  • I will add a photo of the error^^

  • Adapter initialization is correct. In the error it is claimed not to find the Tabspagerarpter class, so check that the package name is correct. For example, in the code I put on the first line is package br.com.exemplo.application.adapter but in your project should be different, something like com.example.teste. Check the contents of the first line package of each class is actually the same as the package name.

  • I think I found the bug.. and in the support library

  • i was using the v4 library and it worked for everything... viewPager.setCurrentItem(tab.getPosition()); does not work from the error

  • just put the line if(viewPager!= null)

  • I made another change to the code, now with the Tab objects being created. Note ai right after pointing to the Viewpager Adapter

  • very good I just found it strange that I can’t use the support library v.13 only to v.4

  • v13 support encompasses v4, so if you go in the directory libs and deleting the v4 library will have no problem keeping only v13.

  • because at the instance of mAdapter = new Tabspageradapter(getSupportFragmentManager()); I am obliged to use the support making it impossible to use the v13 library in Fragmentpageradapter, because mAdapter = new Tabspageradapter(Fragmentmanager()); it does not work

Show 12 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.