編輯:關於 Android 開發
ViewPager 是實現左右滑動切換頁面的經典控件。本課將帶你從零開始,建立一個包含四個子頁面的 ViewPager。
由於 android.support.v4.view 屬於擴展包,因此在布局中使用時,控件的完整名稱也要採用這種寫法。
android:id="@+id/vp_viewpage"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
分別建立 page01.xml、page02.xml、page03.xml、page04.xml,作為 ViewPager 的四個子介面。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#8A2BE2" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:text="page01" android:textSize="40sp" > </TextView> </LinearLayout>
把四個子頁面加入清單,並透過自定義的 PagerAdapter 進行管理。
public class MainActivity extends Activity { private ViewPager viewpager; private List<View> children; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewpager = (ViewPager) findViewById(R.id.vp_viewpage); children = new ArrayList<View>(); children.add(LayoutInflater.from(this).inflate(R.layout.page01, null)); children.add(getLayoutInflater().inflate(R.layout.page02, null)); children.add(getLayoutInflater().inflate(R.layout.page03, null)); children.add(getLayoutInflater().inflate(R.layout.page04, null)); viewpager.setAdapter(new InnerPagerAdapter()); } public class InnerPagerAdapter extends PagerAdapter{ @Override public int getCount() { //獲取子級布局的數量 return children.size();//返回viewpage容器中子級布局的個數, } @Override public boolean isViewFromObject(View view, Object object) { // 判斷某個View對象是否為當前被添加到ViewPager容器中的對象 return view == object; } //下面兩個方法是PageAdapter中必須實現的非抽象方法 @Override public Object instantiateItem(ViewGroup container, int position) { // 實例化ViewPager容器中指定的position位置需要顯示的View對象 View view = children.get(position); container.addView(view); return view; } @Override public void destroyItem(ViewGroup container, int position, Object object) { //在ViewPager中移除指定的position位置的View對象 container.removeView(children.get(position)); } } }完成後即可左右滑動,在多個頁面之間切換。
Android Support v7 學習筆記:FloatingActionButton、RecyclerView 與場景切換
Android Support v7 學習筆記:FloatingActionButton、RecyclerView 與場景切換 Android Support Libra
Android 筆記:Button 點擊事件的五種常見寫法
Android 筆記:Button 點擊事件的五種常見寫法 Button 的點擊事件寫法大致可以歸納為五類,從匿名內部類到直接在 XML 中宣告,各有適用場景。 先準備一
Fragment 學習筆記:生命周期、四種加載方式與 Fragment 間通信
Fragment 學習筆記 Fragment 存在的意義,是為大量型號、尺寸、解析度的設備提供一套統一的 UI 適配方案。把一個龐大的 Activity 拆成若干 Fra
在真機上讀取 /data 目錄並導出 Android 數據庫文件
前提條件 要在真機上查看某個應用的數據庫文件,必須先取得 root 權限,這一步本文不再展開。不同機型與不同 Root 方案的結果可能不一致,筆者手上的設備獲取到的權限如