android學習筆記之ViewPager
阿新 • • 發佈:2019-01-09
簡介
ViewPager:用來滑動切換介面,相當於一個容器,裡面放著你要切換的layout。
佈局檔案
在你需要有滑動切換功能的佈局檔案加入如下程式碼:
<android.support.v4.view.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="wrap_content" > </android.support.v4.view.ViewPager>
之後,就建立你需要的每一個滑動介面,這個滑動介面很簡單,其實就是一個layout檔案,比如建立如下幾個view:
layout1
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="189dp" android:text="view1" /> </RelativeLayout >
layout2
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="189dp" android:text="view2" /> </RelativeLayout >
這裡就不贅述了,想要幾個,就建立幾個就好了。
程式程式碼
首先,要初始化viewpager和view,也就是把佈局檔案和物件對應起來。
viewPager = (ViewPager) findViewById(R.id.viewpager);
LayoutInflater inflater=getLayoutInflater();
view1 = inflater.inflate(R.layout.layout1, null);
view2 = inflater.inflate(R.layout.layout2,null);
view3 = inflater.inflate(R.layout.layout3, null);
然後建立一個view陣列,用來裝這幾個view檔案
viewList = new ArrayList<View>();// 將要分頁顯示的View裝入陣列中
viewList.add(view1);
viewList.add(view2);
viewList.add(view3);
之後,建立一個PageView的介面卡
PagerAdapter pagerAdapter = new PagerAdapter() {
@Override
// 這個函式就是用來告訴框架,這個view的id是不是這個object。
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0 == arg1;
}
@Override
//返回個數
public int getCount() {
// TODO Auto-generated method stub
return viewList.size();
}
@Override
刪除指定view
public void destroyItem(ViewGroup container, int position,
Object object) {
// TODO Auto-generated method stub
container.removeView(viewList.get(position));
}
@Override
//將當前檢視新增到container中,返回view
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
container.addView(viewList.get(position));
return viewList.get(position);
}
};
介面卡的這四個方法需要重寫,其功能已在註釋處寫好,這裡不再贅述。
最後一步,把介面卡新增到你的viewPager。
viewPager.setAdapter(pagerAdapter);