Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 ViewPager + Fragment 打造可滑動的頁籤選單

編輯:關於 Android 程式設計

先看一下成果:

這個範例用 ViewPager 搭配 Fragment 實作了四個頁籤,頂部頁籤可點擊切換,下方有一條白色橫線會隨著切換平移到對應位置,同時滑動時也能同步更新。

1. 建立 TestFragment

每個頁籤就是一個 Fragment。這裡透過靜態 newInstance() 搭配 Bundle 傳入參數,並示範了如何傳遞自訂的 Serializable 物件。

 public class TestFragment extends Fragment { private static final String TAG = "TestFragment"; private String defaultHello = "default value"; private Map<String, Object> maplist; static TestFragment newInstance(String s, Map<String, Object> map) { TestFragment newFragment = new TestFragment(); final SerializableMap myMap = new SerializableMap(); myMap.setMap(map); Bundle bundle = new Bundle(); bundle.putSerializable("map", myMap); newFragment.setArguments(bundle); return newFragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "TestFragment-----onCreate"); SerializableMap serializableMap = (SerializableMap) getArguments().get("map"); maplist = serializableMap.getMap(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(TAG, "TestFragment-----onCreateView"); View view = inflater.inflate(R.layout.lay1, container, false); ListView lv = (ListView) view.findViewById(R.id.listView3); ContactAdapter hc = new ContactAdapter(getActivity().getApplicationContext(), getContact()); lv.setAdapter(hc); lv.setCacheColorHint(0); return view; } private ArrayList<Contact> getContact(){ ArrayList<Contact> hcList = new ArrayList<Contact>(); for(int i=0;i<10;i++) { Contact c0 = new Contact(); c0.setTxPath(R.drawable.more_game+""); c0.setName(maplist.get("userid")+" 年齡:"+maplist.get("age")); hcList.add(c0); } return hcList; } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "TestFragment-----onDestroy"); } } 

提醒一個重點:Fragment 的建構子不能帶參數,資料一律透過 setArguments(Bundle) 傳遞。這是因為系統在記憶體不足回收後重建 Fragment 時,會用無參數建構子重新實例化,帶參數的建構子反而會出錯。

2. MyFragmentPagerAdapter

Adapter 繼承 FragmentPagerAdapter,只需提供 Fragment 清單並實作 getCount() 與 getItem()。

 public class MyFragmentPagerAdapter extends FragmentPagerAdapter { private ArrayList<Fragment> fragmentsList; public MyFragmentPagerAdapter(FragmentManager fm) { super(fm); } public MyFragmentPagerAdapter(FragmentManager fm, ArrayList<Fragment> fragments) { super(fm); this.fragmentsList = fragments; } @Override public int getCount() { return fragmentsList.size(); } @Override public Fragment getItem(int arg0) { return fragmentsList.get(arg0); } @Override public int getItemPosition(Object object) { return super.getItemPosition(object); } } 

3. MainActivity

MainActivity 必須繼承 FragmentActivity。它負責三件事:初始化頁籤文字、初始化 ViewPager、計算白色橫線的移動偏移量。

 public class MainActivity extends FragmentActivity { private static final String TAG = "MainActivity"; private ViewPager mPager; private ArrayList<Fragment> fragmentsList; private ImageView ivBottomLine; private TextView tvTabActivity, tvTabGroups, tvTabFriends, tvTabChat; private int currIndex = 0; private int bottomLineWidth; private int offset = 0; private int position_one, position_two, position_three; private Resources resources; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); resources = getResources(); InitWidth(); InitTextView(); InitViewPager(); } private void InitTextView() { tvTabActivity = (TextView) findViewById(R.id.tv_tab_activity); tvTabGroups = (TextView) findViewById(R.id.tv_tab_groups); tvTabFriends = (TextView) findViewById(R.id.tv_tab_friends); tvTabChat = (TextView) findViewById(R.id.tv_tab_chat); tvTabActivity.setOnClickListener(new MyOnClickListener(0)); tvTabGroups.setOnClickListener(new MyOnClickListener(1)); tvTabFriends.setOnClickListener(new MyOnClickListener(2)); tvTabChat.setOnClickListener(new MyOnClickListener(3)); } private void InitViewPager() { mPager = (ViewPager) findViewById(R.id.vPager); fragmentsList = new ArrayList<Fragment>(); Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("userid","小洪"); paramMap.put("age",23); Map<String, Object> paramMap2 = new HashMap<String, Object>(); paramMap2.put("userid","vatty"); paramMap2.put("age",24); Map<String, Object> paramMap3 = new HashMap<String, Object>(); paramMap3.put("userid","小明"); paramMap3.put("age",25); Map<String, Object> paramMap4 = new HashMap<String, Object>(); paramMap4.put("userid","hongshengpeng.com"); paramMap4.put("age",26); Fragment activityfragment = TestFragment.newInstance("Hello Activity.",paramMap); Fragment groupFragment = TestFragment.newInstance("Hello Group.",paramMap2); Fragment friendsFragment = TestFragment.newInstance("Hello Friends.",paramMap3); Fragment chatFragment = TestFragment.newInstance("Hello Chat.",paramMap4); fragmentsList.add(activityfragment); fragmentsList.add(groupFragment); fragmentsList.add(friendsFragment); fragmentsList.add(chatFragment); mPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentsList)); mPager.setCurrentItem(0); mPager.setOnPageChangeListener(new MyOnPageChangeListener()); } private void InitWidth() { ivBottomLine = (ImageView) findViewById(R.id.iv_bottom_line); bottomLineWidth = ivBottomLine.getLayoutParams().width; Log.d(TAG, "cursor imageview width=" + bottomLineWidth); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int screenW = dm.widthPixels; offset = (int) ((screenW / 4.0 - bottomLineWidth) / 2); position_one = (int) (screenW / 4.0); position_two = position_one * 2; position_three = position_one * 3; } public class MyOnClickListener implements View.OnClickListener { private int index = 0; public MyOnClickListener(int i) { index = i; } @Override public void onClick(View v) { mPager.setCurrentItem(index); } }; public class MyOnPageChangeListener implements OnPageChangeListener { @Override public void onPageSelected(int arg0) { Animation animation = null; switch (arg0) { case 0: if (currIndex == 1) { animation = new TranslateAnimation(position_one, 0, 0, 0); tvTabGroups.setTextColor(resources.getColor(R.color.lightwhite)); } else if (currIndex == 2) { animation = new TranslateAnimation(position_two, 0, 0, 0); tvTabFriends.setTextColor(resources.getColor(R.color.lightwhite)); } else if (currIndex == 3) { animation = new TranslateAnimation(position_three, 0, 0, 0); tvTabChat.setTextColor(resources.getColor(R.color.lightwhite)); } tvTabActivity.setTextColor(resources.getColor(R.color.white)); break; case 1: if (currIndex == 0) { animation = new TranslateAnimation(0, position_one, 0, 0); tvTabActivity.setTextColor(resources.getColor(R.color.lightwhite)); } else if (currIndex == 2) { animation = new TranslateAnimation(position_two, position_one, 0, 0); tvTabFriends.setTextColor(resources.getColor(R.color.lightwhite)); } else if (currIndex == 3) { animation = new TranslateAnimation(position_three, position_one, 0, 0); tvTabChat.setTextColor(resources.getColor(R.color.lightwhite)); } tvTabGroups.setTextColor(resources.getColor(R.color.white)); break; case 2: if (currIndex == 0) { animation = new TranslateAnimation(0, position_two, 0, 0); tvTabActivity.setTextColor(resources.getColor(R.color.lightwhite)); } else if (currIndex == 1) { animation = new TranslateAnimation(position_one, position_two, 0, 0); tvTabGroups.setTextColor(resources.getColor(R.color.lightwhite)); } else if (currIndex == 3) { animation = new TranslateAnimation(position_three, position_two, 0, 0); tvTabChat.setTextColor(resources.getColor(R.color.lightwhite)); } tvTabFriends.setTextColor(resources.getColor(R.color.white)); break; case 3: if (currIndex == 0) { animation = new TranslateAnimation(0, position_three, 0, 0); tvTabActivity.setTextColor(resources.getColor(R.color.lightwhite)); } else if (currIndex == 1) { animation = new TranslateAnimation(position_one, position_three, 0, 0); tvTabGroups.setTextColor(resources.getColor(R.color.lightwhite)); } else if (currIndex == 2) { animation = new TranslateAnimation(position_two, position_three, 0, 0); tvTabFriends.setTextColor(resources.getColor(R.color.lightwhite)); } tvTabChat.setTextColor(resources.getColor(R.color.white)); break; } currIndex = arg0; animation.setFillAfter(true); animation.setDuration(300); ivBottomLine.startAnimation(animation); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } } } 

這裡的關鍵是 InitWidth():先用 DisplayMetrics 取得螢幕寬度,除以頁籤數量得到每格寬度,再算出橫線需要水平居中的 offset,以及三個切換位置 position_one/two/three。有了這組數字,TranslateAnimation 就能精準地把橫線推到目標頁籤下方。另外別忘了 animation.setFillAfter(true),否則動畫結束後橫線會跳回原點。

4. 版面配置

lay1.xml 放的是頁籤一的內容(這裡用一個 ListView 承載資料):

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#fff" android:orientation="vertical"> <ListView android:id="@+id/listView3" android:layout_width="match_parent" android:layout_height="wrap_content" android:cacheColorHint="@android:color/transparent" android:divider="@drawable/reader_item_divider" android:listSelector="@android:color/transparent"> </ListView> </LinearLayout>

lay2.xml 與 lay3.xml 結構相同,只是背景色不同(分別為 #FF8684 與 #1586FF),用來清楚區分頁籤:

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="#FF8684"> </LinearLayout>

main.xml 的上半部是四個頁籤文字,下半部是白色橫線 ImageView,最下方才是 ViewPager:

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="48dip" android:background="@drawable/android_title_bg"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginLeft="10dip" android:text="樂夠GO" /> </LinearLayout> <LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@color/coral"> <TextView android:id="@+id/tv_tab_activity" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1.0" android:gravity="center" android:text="動態" android:textColor="@color/white" android:textSize="18sp" /> <TextView android:id="@+id/tv_tab_groups" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1.0" android:gravity="center" android:text="群組" android:textColor="@color/lightwhite" android:textSize="18sp" /> <TextView android:id="@+id/tv_tab_friends" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1.0" android:gravity="center" android:text="好友" android:textColor="@color/lightwhite" android:textSize="18sp" /> <TextView android:id="@+id/tv_tab_chat" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1.0" android:gravity="center" android:text="聊天" android:textColor="@color/lightwhite" android:textSize="18sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingBottom="3dip"> <ImageView android:id="@+id/iv_bottom_line" android:layout_width="40dip" android:layout_height="2dip" android:layout_marginLeft="20dip" android:scaleType="matrix" android:src="#fff" /> </LinearLayout> <android.support.v4.view.ViewPager android:id="@+id/vPager" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_weight="1.0" android:flipInterval="30" android:persistentDrawingCache="animation" /> </LinearLayout>

補充:更精簡的 ViewPager + Fragment 寫法

如果你只是想快速做一個可滑動的頁籤頁,其實可以更省事。版面配置如下:

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/tv_guid1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0" android:gravity="center" android:text="特性1" android:textSize="18sp"/> <TextView android:id="@+id/tv_guid2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0" android:gravity="center" android:text="特性2" android:textSize="18sp"/> <TextView android:id="@+id/tv_guid3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0" android:gravity="center" android:text="特性3" android:textSize="18sp"/> <TextView android:id="@+id/tv_guid4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0" android:gravity="center" android:text="特性4" android:textSize="18sp"/> </LinearLayout> <ImageView android:id="@+id/cursor" android:layout_width="wrap_content" android:layout_height="wrap_content" android:scaleType="matrix" android:src="@drawable/cursor"/> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="fill_parent" android:layout_height="fill_parent" android:flipInterval="30" android:persistentDrawingCache="animation"/> </LinearLayout> 

程式碼部分:

 public class MainActivity extends FragmentActivity { private ViewPager mPager; private ArrayList<Fragment> fragmentList; private ImageView image; private TextView view1, view2, view3, view4; private int currIndex;//當前頁卡編號 private int bmpW;//橫線圖片寬度 private int offset;//圖片移動的偏移量 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); InitTextView(); InitImage(); InitViewPager(); } /* 初始化標簽名 */ public void InitTextView(){ view1 = (TextView)findViewById(R.id.tv_guid1); view2 = (TextView)findViewById(R.id.tv_guid2); view3 = (TextView)findViewById(R.id.tv_guid3); view4 = (TextView)findViewById(R.id.tv_guid4); view1.setOnClickListener(new txListener(0)); view2.setOnClickListener(new txListener(1)); view3.setOnClickListener(new txListener(2)); view4.setOnClickListener(new txListener(3)); } public class txListener implements View.OnClickListener{ private int index=0; public txListener(int i) { index =i; } @Override public void onClick(View v) { mPager.setCurrentItem(index); } } /* 初始化圖片的位移像素 */ public void InitImage(){ image = (ImageView)findViewById(R.id.cursor); bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.cursor).getWidth(); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int screenW = dm.widthPixels; offset = (screenW/4 - bmpW)/2; //imgageview設置平移,使下劃線平移到初始位置 Matrix matrix = new Matrix(); matrix.postTranslate(offset, 0); image.setImageMatrix(matrix); } /* 初始化ViewPager */ public void InitViewPager(){ mPager = (ViewPager)findViewById(R.id.viewpager); fragmentList = new ArrayList<Fragment>(); Fragment btFragment = new ButtonFragment(); Fragment secondFragment = TestFragment.newInstance("this is second fragment"); Fragment thirdFragment = TestFragment.newInstance("this is third fragment"); Fragment fourthFragment = TestFragment.newInstance("this is fourth fragment"); fragmentList.add(btFragment); fragmentList.add(secondFragment); fragmentList.add(thirdFragment); fragmentList.add(fourthFragment); mPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentList)); mPager.setCurrentItem(0); mPager.setOnPageChangeListener(new MyOnPageChangeListener()); } public class MyOnPageChangeListener implements OnPageChangeListener{ private int one = offset * 2 + bmpW;//兩個相鄰頁面的偏移量 @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } @Override public void onPageSelected(int arg0) { Animation animation = new TranslateAnimation(currIndex*one,arg0*one,0,0);//平移動畫 currIndex = arg0; animation.setFillAfter(true);//停留最後一幀 animation.setDuration(200); image.startAnimation(animation); int i = currIndex + 1; Toast.makeText(MainActivity.this, "您選擇了第"+i+"個頁卡", Toast.LENGTH_SHORT).show(); } } }

Adapter 與 Fragment 都很單純:

 public class MyFragmentPagerAdapter extends FragmentPagerAdapter{ ArrayList<Fragment> list; public MyFragmentPagerAdapter(FragmentManager fm, ArrayList<Fragment> list) { super(fm); this.list = list; } @Override public int getCount() { return list.size(); } @Override public Fragment getItem(int arg0) { return list.get(arg0); } }

public class TestFragment extends Fragment { private String hello; private String defaultHello = "default value"; static TestFragment newInstance(String s) { TestFragment newFragment = new TestFragment(); Bundle bundle = new Bundle(); bundle.putString("hello", s); newFragment.setArguments(bundle); return newFragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle args = getArguments(); hello = args != null ? args.getString("hello") : defaultHello; View view = inflater.inflate(R.layout.guide_2, container, false); TextView viewhello = (TextView) view.findViewById(R.id.tv); viewhello.setText(hello); return view; } }

Adapter 該選哪一個?

Google 官方建議 ViewPager 與 Fragment 搭配使用,此時 Adapter 是 FragmentPagerAdapter,至少必須覆寫:

getCount() 與 getItem()

若 ViewPager 不搭配 Fragment,則 Adapter 改用 PagerAdapter,它是直接填充 View 的基底類別,至少必須覆寫:

instantiateItem(ViewGroup, int)、destroyItem(ViewGroup, int, Object)、getCount()、isViewFromObject(View, Object)

兩者的取捨在於記憶體策略:FragmentPagerAdapter 會把 Fragment 保留在 FragmentManager 中,頁面數量不多時最省事;若頁籤很多、每頁都很重,則該考慮 FragmentStatePagerAdapter,它會在頁面被移除時一併銷毀 Fragment 狀態,記憶體佔用更低。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved