1234abcd 1234abcd - 1 year ago 72
Android Question

How to show fragment in android

I am using ViewPager to create 3 Fragment on Activity1,

this is my viewPager adapter :

public class ViewPagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;

public ViewPagerAdapter(FragmentManager fm, int NumOfTabs) {
this.mNumOfTabs = NumOfTabs;

public Fragment getItem(int position) {

switch (position) {
case 0:
Fragment1 tab1 = new Fragment1();
return tab1;
case 1:
Fragment2 tab2 = new Fragment2();
return tab2;
case 2:
Fragment3 tab3 = new Fragment3();
return tab3;
return null;

public int getCount() {
return mNumOfTabs;


this is Activity :

protected void onCreate(Bundle savedInstanceState) {

TabLayout tab_layout = (TabLayout) findViewById(R.id.tab_layout);

final ViewPager view_pager = (ViewPager) findViewById(R.id.viewpager);

final ViewPagerAdapter adapter = new ViewPagerAdapter
(getSupportFragmentManager(), tab_layout.getTabCount());


view_pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tab_layout));

tab_layout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

public void onTabSelected(TabLayout.Tab tab) {

public void onTabUnselected(TabLayout.Tab tab) {

public void onTabReselected(TabLayout.Tab tab) {


When Activity1 is open it show Fragment1 . But I want to show Fragment2 or Fragment3 instead .

How I can to do that?

Answer Source

Add this line after viewpager.setAdapter(adapter); :


Index is depending on you , how many fragments you have. tabLayout.getTabCount(); will return you tab count. But index is starting from 0.

If you have 3 Fragment and want to show third Fragment you must use viewPager.setCurrentItem(2);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download