編輯:關於 Android 程式設計
先前寫過〈Android 中使用 ViewFlipper 實現屏幕切換〉。相比 ViewFlipper,ViewPager 更適合複雜的視圖切換,而且它有自己的 Adapter 體系,能輕鬆處理動態資料載入。
ViewPager 是 Google 官方為相容舊版裝置而提供的支援庫元件(早期位於 support-v4),讓 3.0 以下的系統也能用上新 API。從最簡單的導覽列到複雜的頁面選單,它都能勝任。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://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:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:id="@+id/vp">
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tap">
</android.support.v4.view.PagerTabStrip>
</android.support.v4.view.ViewPager>
</LinearLayout>
四個容易出錯的細節:
ClassNotFoundException。android:layout_gravity="TOP|BOTTOM" 指定標題的位置。getPageTitle(int)。 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@mipmap/a1"
android:scaleType="centerCrop"
android:id="@+id/iv1" />
</LinearLayout>
做法是實作一個 PagerAdapter,必須覆寫的四個方法如下:
instantiateItem(ViewGroup, int):具現化該頁destroyItem(ViewGroup, int, Object):移除該頁getCount():回傳頁數isViewFromObject(View, Object):判斷物件是否為該頁的 View若要顯示 PagerTabStrip 的標題,再加上 getPageTitle(int position)。指示器樣式則可用 setTabIndicatorColor()、setBackgroundColor()、setTextColor() 調整。
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class ViewPagerDemo extends AppCompatActivity {
private ViewPager vp;
// 存放各頁 View 的集合
ArrayList<View> views = new ArrayList<>();
// 各頁的標題
String[] titles = { "一號美女", "二號美女", "三號美女", "四號美女" };
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpager_layout);
vp = (ViewPager) findViewById(R.id.vp);
initView(); // 初始化各頁 View
vp.setAdapter(new MyAdapter());
}
// 透過 LayoutInflater 載入各頁版面並存入集合
private void initView() {
View v1 = getLayoutInflater().inflate(R.layout.layout1, null);
View v2 = getLayoutInflater().inflate(R.layout.layout2, null);
View v3 = getLayoutInflater().inflate(R.layout.layout3, null);
View v4 = getLayoutInflater().inflate(R.layout.layout4, null);
views.add(v1);
views.add(v2);
views.add(v3);
views.add(v4);
}
class MyAdapter extends PagerAdapter {
@Override
public int getCount() {
return views.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
// 銷毀該頁:從容器中移除
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(views.get(position));
}
// 初始化該頁:從集合取出 View 並加入容器
@Override
public Object instantiateItem(ViewGroup container, int position) {
View v = views.get(position);
container.addView(v);
return v;
}
@Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
}

開始之前先說明兩點:這裡未實作無限循環;導航圓點的資源 default_holo 為未選中狀態、touched_holo 為選中後的實心狀態(也可以自行用 Shape 繪製)。
主容器用 FrameLayout,ViewPager 之上疊一個包含三個導航圓點的 LinearLayout(圓點數量由頁面數決定,置於底部):
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.administrator.myapplication11.MainActivity">
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/vp">
</android.support.v4.view.ViewPager>
<LinearLayout
android:id="@+id/point_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:orientation="horizontal">
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@mipmap/default_holo"/>
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@mipmap/default_holo" />
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@mipmap/default_holo"
android:id="@+id/imageView" />
</LinearLayout>
</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@mipmap/genie"/>
</LinearLayout>
透過實作 ViewPager.OnPageChangeListener,在頁面切換時同步更新圓點狀態(各個回呼的詳細說明可參考〈ViewPager 的 setOnPageChangeListener 方法詳解〉)。
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {
private ViewPager vp;
private LinearLayout point_layout;
ArrayList<View> views = new ArrayList<>();
ArrayList<ImageView> imageViews = new ArrayList<>(); // 存放導航圓點
int currImage; // 記錄目前所在頁
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vp = (ViewPager) findViewById(R.id.vp);
initView(); // 初始化各頁 View
initPoint(); // 初始化導航圓點
vp.addOnPageChangeListener(this);
vp.setAdapter(new MyAdapter());
}
/**
* 把 point_layout 中的 ImageView 收集起來,
* 並把第 0 頁對應的圓點設為 touched_holo(選中狀態)
*/
private void initPoint() {
point_layout = (LinearLayout) findViewById(R.id.point_layout);
int counnt = point_layout.getChildCount();
for (int i = 0; i < counnt; i++) {
imageViews.add((ImageView) point_layout.getChildAt(i));
}
imageViews.get(0).setImageResource(R.mipmap.touched_holo);
}
private void initView() {
View v1 = getLayoutInflater().inflate(R.layout.layout1, null);
View v2 = getLayoutInflater().inflate(R.layout.layout2, null);
View v3 = getLayoutInflater().inflate(R.layout.layout3, null);
views.add(v1);
views.add(v2);
views.add(v3);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// 這裡不做處理
}
// 切換到某頁後,更新圓點狀態
@Override
public void onPageSelected(int position) {
ImageView preView = imageViews.get(currImage);
preView.setImageResource(R.mipmap.default_holo);
ImageView currView = imageViews.get(position);
currView.setImageResource(R.mipmap.touched_holo);
currImage = position;
}
@Override
public void onPageScrollStateChanged(int state) {
// 這裡不做處理
}
class MyAdapter extends PagerAdapter {
@Override
public int getCount() {
return views.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(views.get(position));
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View v = views.get(position);
container.addView(v);
return v;
}
}
}
以上只是 ViewPager 最基礎的用法。若要 production 等級的實作,建議留意幾點:
FragmentStateAdapter,也告別了 PagerAdapter 那套容易寫錯的 destroy / instantiate 邏輯。FragmentPagerAdapter 或 FragmentStateAdapter,並避免在 instantiateItem() 裡自行管理 Fragment 生命週期。Handler.postDelayed() 定時呼叫 setCurrentItem(),並在 onPause() 移除 callbacks。
Android 與伺服器通訊:如何確保兩端時間一致
需求背景 在 AChat 專案的開發過程中,需求要求:無論終端處於哪個時區、所在何地、系統時間是否正確,POST 到伺服器的資料包中的時間欄位都必須與伺服器同步。也就是說
Android 藍牙完全學習手冊:從協議到源碼剖析
1. 前言 市面上關於 Android 的技術書籍眾多,幾乎每本都會涉及藍牙開發,但多為上層應用層面,篇幅也普遍偏短。對於手機行業的開發者而言,要維護藍牙模組,就必須從系
RxJava2 核心變化全解析
最近剛把 RxJava1.x 的源碼讀完,正好 RxJava2.x 也放出了 RC 版本。趁著正式版發布前的空檔,本文就來對 RxJava2.x 做一次入門級的剖析。
Android View 源碼剖析:requestLayout、invalidate 與 postInvalidate 的差異
requestLayout:請求重新布局當 View 的大小、位置或可見狀態可能改變時,可以呼叫 requestLayout。它會從目前 View 開始,沿著父容器層層向