1.在項(xiàng)目中添加V4包
引用v4包中的ViewPager控件窒百。
或者添加android.support.v4.view.ViewPager
2.在activity_main.xml布局中添加ViewPager:
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
3.創(chuàng)建適配器MyViewPagerAdapter
public class MyViewPagerAdapter extends PagerAdapter {
private List<View> mListViews;
public MyViewPagerAdapter(List<View> mListViews) {
this.mListViews = mListViews;//構(gòu)造方法浮定,參數(shù)是我們的頁卡,這樣比較方便雨饺。
}
//直接繼承PagerAdapter磕洪,至少必須重寫下面的四個(gè)方法鸵荠,否則會(huì)報(bào)錯(cuò)
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(mListViews.get(position));//刪除頁卡
}
@Override
public Object instantiateItem(ViewGroup container, int position){
//這個(gè)方法用來實(shí)例化頁卡
container.addView(mListViews.get(position), 0);//添加頁卡
return mListViews.get(position);
}
@Override
public int getCount() {
return mListViews.size();//返回頁卡的數(shù)量
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0==arg1;//官方提示這樣寫
}
}
4.在MainActivity調(diào)用
public class MainActivity extends AppCompatActivity {
private View view1;
private View view2;
private View view3;
private List<View> viewList;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
initPager();
}
private void initPager() {
LayoutInflater lf = getLayoutInflater().from(this);
view1 = lf.inflate(R.layout.activity_one, null);
view2 = lf.inflate(R.layout.activity_two, null);
view3 = lf.inflate(R.layout.activity_three, null);
viewList = new ArrayList<View>();// 將要分頁顯示的View裝入數(shù)組中
viewList.add(view1);
viewList.add(view2);
viewList.add(view3);
viewPager.setAdapter(new MyViewPagerAdapter(viewList));
}
}