layout文件的设置
<android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_centerVertical="true" android:layout_width="wrap_content" android:layout_height="wrap_content"> <android.support.v4.view.PagerTabStrip android:id="@+id/tab" android:layout_marginTop="@dimen/activity_vertical_margin" android:layout_width="wrap_content" android:layout_height="wrap_content"> </android.support.v4.view.PagerTabStrip> </android.support.v4.view.ViewPager>
PagerTabStrip必须定义在viewpager之中,否则报错
在Activity的定义之中
public class MainActivity extends Activity { private List<View> list; private List<String>titlelist; private PagerTitleStrip tabStrip; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); list= new ArrayList<View>(); titlelist=new ArrayList<String>(); tabStrip=(PagerTitleStrip)findViewById(R.id.tab); /** * 通过view对象作为viewpager的数据源 */ View view1=View.inflate(this,R.layout.view1,null); View view2=View.inflate(this,R.layout.view2,null); View view3=View.inflate(this,R.layout.view3,null); View view4=View.inflate(this,R.layout.view4,null); list.add(view1); list.add(view2); list.add(view3); list.add(view4); titlelist.add("1"); titlelist.add("2"); titlelist.add("3"); titlelist.add("5"); //设置title的样式 tabStrip.setBackgroundColor(Color.WHITE); tabStrip.setTextColor(Color.BLUE); tabStrip.setDrawingCacheBackgroundColor(Color.YELLOW); //创建pageadapter,在调用Mypageadapter的对象时加上定义的titlelist Mypageadapter mypageadapter= new Mypageadapter(list,titlelist); //初始化viewpager ViewPager pager= (ViewPager)findViewById(R.id.viewpager); //加载适配器 pager.setAdapter(mypageadapter); } }
在Pageadapter之中加入调用标题的方法
public CharSequence getPageTitle(int position) { return titlelist.get(position); }
pageradapter代码
public class Mypageadapter extends PagerAdapter { private List<View> viewList; private List<String>titlelist; public Mypageadapter(List<View>viewList,List<String>titlelist){ this.viewList=viewList; this.titlelist=titlelist; } //返回页卡的数量 @Override public int getCount() { return viewList.size(); } //page是否来自于对象 @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); } }