1234abcd 1234abcd - 5 months ago 14
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) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}

@Override
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;
default:
return null;
}
}

@Override
public int getCount() {
return mNumOfTabs;
}

}


this is Activity :

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);

TabLayout tab_layout = (TabLayout) findViewById(R.id.tab_layout);
tab_layout.addTab(tab_layout.newTab().setText("Frag1"));
tab_layout.addTab(tab_layout.newTab().setText("Frag2"));
tab_layout.addTab(tab_layout.newTab().setText("Frag3"));

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

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

view_pager.setAdapter(adapter);

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

tab_layout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

@Override
public void onTabSelected(TabLayout.Tab tab) {
view_pager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(TabLayout.Tab tab) {
}

@Override
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

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

viewPager.setCurrentItem(index);

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

Comments