原文地址:http://blog.csdn.net/crazy1235/article/details/42678877
效果:滑动切换;点击标签切换。
代码:https://github.com/ldb-github/Layout_Tab
1、使用ViewPager和PagerTabStrip/PagerTitleStrip进行布局。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"> <android.support.v4.view.ViewPager
android:id="@+id/fifth_vp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"> <android.support.v4.view.PagerTabStrip
android:id="@+id/fifth_strip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#7EC0EE"
android:padding="10dp"/> </android.support.v4.view.ViewPager>
</LinearLayout>
viewpager_pagertitle_pagertab.xml
1、要实现PagerAdapter的getPageTitle()方法,此方法提供了标签名称。
2、PaperTabStrip是PagerTitleStrip的子类,它添加了指示器功能,也就是标签下面的小矩阵。
public class ViewPagerAndPagerTitleOrPagerTabActivity extends Activity{ // viewpager
private ViewPager viewPager;
// viewpager的标题 使用PagerTitleStrip只需要把Lyaout文件中的PagerTabStrip改为PagerTitleStrip
private PagerTitleStrip titleStrip;
// viewpager的指示器
private PagerTabStrip tabStrip;
// view集合
private List<View> viewList;
// 标题集合
private List<String> titleList; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpager_pagertitle_pagertab); init();
} private void init(){
viewList = new ArrayList<>();
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.viewpager_pageradapter_tab1, null);
viewList.add(view);
view = inflater.inflate(R.layout.viewpager_pageradapter_tab2, null);
viewList.add(view);
view = inflater.inflate(R.layout.viewpager_pageradapter_tab3, null);
viewList.add(view); titleList = new ArrayList<>();
titleList.add("标题1");
titleList.add("标题2");
titleList.add("标题3"); initViewPager();
}
private void initViewPager(){
viewPager = (ViewPager) findViewById(R.id.fifth_vp);
viewPager.setAdapter(pagerAdapter); // 修改指示器的颜色
// tabStrip = (PagerTabStrip) findViewById(R.id.fifth_strip);
// tabStrip.setTabIndicatorColor(Color.RED); } /**
* 适配器
*/
PagerAdapter pagerAdapter = new PagerAdapter() {
@Override
public int getCount() {
return viewList.size();
} @Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
} @Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(viewList.get(position));
return viewList.get(position);
} @Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(viewList.get(position));
} @Override
public CharSequence getPageTitle(int position) {
return titleList.get(position);
}
};
}
ViewPagerAndPagerTitleOrPagerTabActivity.java