編輯:關於 Android 開發
本文整理自一篇經典的 ViewPager + Fragment 範例,適合想快速做出左右滑動分頁效果的入門者參考。
先來理解 Fragment 的定位:它是為了簡化 Activity 與 View 之間的互動,將 Activity 中與使用者互動的邏輯模組化封裝而生的。它的好處在於:其一,能簡化 Activity 的邏輯控制;其二,這些模組化的 Fragment 更利於重複使用。
Fragment 的主要特點包括:
下圖為運行效果:

需要注意的是,範例代碼本身能正常運行,但當你往 ViewPager 中傳入動態數據時,可能會遇到數據顯示不對應、甚至有頁面不顯示的情況。網路上常見的說法是:需要重寫 FragmentPagerAdapter 的 instantiateItem 方法。這部分可以作為進階研究的方向。
以下是主要的版面配置檔:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#eee" >
<LinearLayout android:id="@+id/ll_main_text"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#FF7200"
android:gravity="center_vertical" >
<LinearLayout android:layout_width="60dp"
android:layout_height="match_parent" android:gravity="center" >
<ImageView android:layout_width="30dp"
android:layout_height="30dp"
android:contentDescription="@null"
android:scaleType="fitCenter"
android:src="@drawable/arrow_left" />
</LinearLayout>
<View android:layout_width="0.5dp"
android:layout_height="match_parent" android:background="#FE8B40" />
<TextView android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.8" android:gravity="center"
android:text="限時購" android:textColor="@android:color/white"
android:textSize="20sp" />
<View android:layout_width="0.5dp"
android:layout_height="match_parent" android:background="#FE8B40" />
<LinearLayout android:layout_width="60dp"
android:layout_height="match_parent" android:gravity="center" >
<ImageView android:layout_width="30dp"
android:layout_height="30dp"
android:contentDescription="@null"
android:scaleType="fitCenter"
android:src="@drawable/dropdown" />
</LinearLayout>
</LinearLayout>
<LinearLayout android:id="@+id/ll_text_mainout"
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_alignParentBottom="true"
android:background="#eee" android:gravity="center_vertical"
android:orientation="vertical" >
<View android:layout_width="match_parent"
android:layout_height="0.5dp" android:background="#999999" />
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false" android:gravity="center"
android:orientation="horizontal" >
<RelativeLayout android:layout_width="0dp"
android:layout_height="match_parent" android:layout_weight="1" >
<Button android:id="@+id/bb_text_main1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawableTop="@drawable/main_topcolor"
android:paddingBottom="2dp" android:paddingTop="5dp"
android:text="限時搶購"
android:textColor="@color/main_bottoncolor" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/ll_text_mainout"
android:layout_below="@id/ll_main_text"
android:background="@android:color/white"
android:orientation="vertical" >
<LinearLayout android:id="@+id/linearlayout1"
android:layout_width="match_parent"
android:layout_height="50.0dip"
android:layout_gravity="center"
android:background="#FFFFFF" >
<TextView android:id="@+id/text1"
android:layout_width="0dp" android:layout_height="match_parent"
android:layout_weight="1.0" android:gravity="center"
android:text="頁卡1" android:textColor="#000000"
android:textSize="22.0dip" />
<TextView android:id="@+id/text2"
android:layout_width="0dp" android:layout_height="match_parent"
android:layout_weight="1.0" android:gravity="center"
android:text="頁卡2" android:textColor="#000000"
android:textSize="22.0dip" />
<TextView android:id="@+id/text3"
android:layout_width="0dp" android:layout_height="match_parent"
android:layout_weight="1.0" android:gravity="center"
android:text="頁卡3" android:textColor="#000000"
android:textSize="22.0dip" />
</LinearLayout>
<TextView android:id="@+id/cursor"
android:layout_width="100dp" android:layout_height="5dp"
android:background="#990033" />
<android.support.v4.view.ViewPager
android:id="@+id/vPager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" android:background="#000000"
android:flipInterval="30"
android:persistentDrawingCache="animation" />
</LinearLayout>
</RelativeLayout>
主要 Activity 代碼如下,重點在於初始化頁卡標籤、頁卡指示條,以及為 ViewPager 設定 FragmentPagerAdapter:
package org.xml.demo.viewpager;
import java.util.ArrayList;
import ogg.huanxin.huadong.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class MyViewpager extends FragmentActivity {
private ViewPager mPager;
private TextView barText;
private TextView view1, view2, view3;
private ArrayList<Fragment> fragmentlist;
private int currIndex; // 當前的頁卡標號
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mypager);
InitTextView();
InitTextBar();
InitViewPager();
}
/* 初始化標籤名字 */
private void InitTextView() {
view1 = (TextView) findViewById(R.id.text1);
view2 = (TextView) findViewById(R.id.text2);
view3 = (TextView) findViewById(R.id.text3);
view1.setOnClickListener(new txListener(0));
view2.setOnClickListener(new txListener(1));
view3.setOnClickListener(new txListener(2));
}
public class txListener implements View.OnClickListener {
private int index = 0;
public txListener(int i) { index = i; }
@Override
public void onClick(View arg0) {
mPager.setCurrentItem(index);
}
}
/* 初始化圖片的位移像素 */
private void InitTextBar() {
barText = (TextView) super.findViewById(R.id.cursor);
Display display = getWindow().getWindowManager().getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
int tabLimeLength = metrics.widthPixels / 3;
LayoutParams lp = (LayoutParams) barText.getLayoutParams();
lp.width = tabLimeLength;
barText.setLayoutParams(lp);
}
/* 初始化 ViewPager */
private void InitViewPager() {
mPager = (ViewPager) findViewById(R.id.vPager);
fragmentlist = new ArrayList<Fragment>();
Fragment btFragment = new Fragment1();
Fragment fragment2 = new Fragment2();
Fragment fragment3 = new Fragment3();
fragmentlist.add(btFragment);
fragmentlist.add(fragment2);
fragmentlist.add(fragment3);
mPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentlist));
mPager.setCurrentItem(0);
mPager.setOnPageChangeListener(new MyOnpageChangeListener());
}
private class MyOnpageChangeListener implements OnPageChangeListener {
@Override
public void onPageScrollStateChanged(int arg0) {
// 0(END), 1(PRESS), 2(UP)
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// arg0 目標頁, arg1 偏移百分比, arg2 偏移像素
LinearLayout.LayoutParams ll = (LayoutParams) barText.getLayoutParams();
if (currIndex == arg0) {
ll.leftMargin = (int) (currIndex * barText.getWidth() + arg1 * barText.getWidth());
} else if (currIndex > arg0) {
ll.leftMargin = (int) (currIndex * barText.getWidth() - (1 - arg1) * barText.getWidth());
}
barText.setLayoutParams(ll);
}
@Override
public void onPageSelected(int arg0) {
currIndex = arg0;
}
}
private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> list;
public MyFragmentPagerAdapter(FragmentManager fm, ArrayList<Fragment> list) {
super(fm);
this.list = list;
}
@Override
public Fragment getItem(int arg0) { return list.get(arg0); }
@Override
public int getCount() { return list.size(); }
}
}
其中單個 Fragment 的寫法如下,三個 Fragment 你可以自由發揮。這個 Fragment 內部放置了一個自定義的 GridView:

package org.xml.demo.viewpager;
import org.xml.demo.MyGridView;
import org.xml.demo.ProducteGridAdapter;
import ogg.huanxin.huadong.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
public class Fragment1 extends Fragment {
private MyGridView myGridView;
private ProducteGridAdapter producteGridAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setFindViewById();
setListener();
}
private void setFindViewById() {
myGridView = (MyGridView) getActivity().findViewById(R.id.my_fragment1_view);
producteGridAdapter = new ProducteGridAdapter(getActivity());
myGridView.setAdapter(producteGridAdapter);
}
private void setListener() {
myGridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getActivity(), "你點擊了" + arg2, Toast.LENGTH_SHORT).show();
}
});
}
}
對應的 Fragment 版面配置:
<?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:orientation="vertical" >
<ImageView android:layout_width="match_parent"
android:layout_height="100dp"
android:contentDescription="@null" android:visibility="gone"
android:scaleType="fitCenter" android:src="@drawable/a" />
<ScrollView android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content" android:orientation="vertical" >
<org.xml.demo.MyGridView android:id="@+id/my_fragment1_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:horizontalSpacing="4dp" android:numColumns="2"
android:verticalSpacing="7dp" >
</org.xml.demo.MyGridView>
</LinearLayout>
</ScrollView>
</LinearLayout>
透過 ViewPager 承載多個 Fragment,再搭配 OnPageChangeListener 動態移動頁卡指示條,就能做出流暢的左右滑動分頁體驗。掌握這個範式後,你可以自由替換每個 Fragment 的內容,靈活組出各式分頁介面。
VS2015 搭建 ionic2 環境進階篇:用 nrm 換源後暢通無阻
VS2015 搭建 ionic2 環境進階篇:用 nrm 換源後暢通無阻 上一篇講了 VS2015 牆內創建 ionic2 的基本流程,但由於 npm 源在國際線路上,速
RxJava 與 RxAndroid(四):用 RxBinding 把控件事件變成流
RxJava 與 RxAndroid(四):用 RxBinding 把控件事件變成流 先補上前面幾篇 對 RxJava 還不熟的同學,建議先看這個系列的前三篇: RxJ
手寫控件拖拽:讓 ImageView 跟著手指跑,雙擊還能水平居中
懸浮視窗、桌面小工具、可移動的浮動按鈕,本質上都是同一件事:讓一個 View 跟著手指移動。這個範例用一個 ImageView 示範完整做法,並額外加上「雙擊水平居中」的
Android 源碼分享:舊版陌陌專案的登入註冊實作
想找一個「規模不大、但功能完整」的 Android 練習專案?這份早期版本的陌陌仿作正好是那種類型。它沒有龐大的第三方依賴,卻把一個社群應用最基礎的環節——帳號註冊與登入