TabBar_ViewPager做成的tab页面




//DEMO

public class MainActivity extends FragmentActivity implements TabListener {
ViewPager viewPager;
ActionBar bar;

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

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

Fragment[] fragmentArray = new Fragment[] { new AFragmentTab(),
new BFragmentTab(), new CFragmentTab() };
HKFragmentPagerAdapter adapter = new HKFragmentPagerAdapter(
getSupportFragmentManager(), fragmentArray);

viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {

@Override
public void onPageSelected(int position) {
bar.setSelectedNavigationItem(position);
}

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

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

bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// fragmentArray.length()是多少,这里就是多少个TAB
ActionBar.Tab tabA = bar.newTab().setText("A Tab");
ActionBar.Tab tabB = bar.newTab().setText("B Tab");
ActionBar.Tab tabC = bar.newTab().setText("C Tab");
tabA.setTabListener(this);
tabB.setTabListener(this);
tabC.setTabListener(this);
bar.addTab(tabA);
bar.addTab(tabB);
bar.addTab(tabC);
}

public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}

public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}

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

}


标准的FragmentPagerAdapter适配器
public class HKFragmentPagerAdapter extends FragmentPagerAdapter {
Fragment[] fragmentArray;

public HKFragmentPagerAdapter(FragmentManager fm, Fragment[] fragmentArray) {
super(fm);
if (null == fragmentArray) {
this.fragmentArray = new Fragment[] {};
} else {
this.fragmentArray = fragmentArray;
}
}

@Override
public Fragment getItem(int position) {
return fragmentArray[position];
}

@Override
public int getCount() {
return fragmentArray.length;
}
}


//Fragment的写法
public class AFragmentTab extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_a, container, false);
}
}


你可能感兴趣的:(android)