編輯:關於 Android 程式設計
這個系列的第三篇,要把首頁拼出來:最外層三個 Tab(精選、訂閱、發現),精選頁頂部是自動輪播的圖片廣告,廣告下方是文章列表。

這裡用 ViewPager 承載三個 Fragment,可左右滑動切換,並省去手動管理 Fragment 顯示隱藏的麻煩。
結構很單純:上方是含三個 TextView 的 RelativeLayout,下方是 ViewPager。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white_normal">
<RelativeLayout
android:id="@+id/ll_title"
android:layout_width="match_parent"
android:layout_height="44dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/main_color"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_selected"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="精選"
android:textColor="@drawable/main_title_txt_sel" />
<TextView
android:id="@+id/tv_subscribe"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="訂閱"
android:textColor="@drawable/main_title_txt_sel" />
<TextView
android:id="@+id/tv_find"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="發現"
android:textColor="@drawable/main_title_txt_sel" />
</LinearLayout>
<View
android:id="@+id/view_indicator"
android:layout_width="15dp"
android:layout_height="2dp"
android:layout_alignParentBottom="true"
android:background="@color/white_normal" />
</RelativeLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager_home"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/ll_title" />
</RelativeLayout>
vPager = (ViewPager) rootView.findViewById(R.id.viewpager_home); SelectedFragment selectedFragment = new SelectedFragment(); SubscribeFragment subscribeFragment = new SubscribeFragment(); FindFragment findFragment = new FindFragment(); List<Fragment> list = new ArrayList<>(); list.add(selectedFragment); list.add(subscribeFragment); list.add(findFragment); adapter = new FragmentAdapter(getActivity().getSupportFragmentManager(), list); vPager.setAdapter(adapter); vPager.setOffscreenPageLimit(2); vPager.setCurrentItem(0); vPager.setOnPageChangeListener(pageChangeListener);
繼承 FragmentStatePagerAdapter 即可,實作非常薄:
public class FragmentAdapter extends FragmentStatePagerAdapter {
private List<Fragment> list;
public FragmentAdapter(FragmentManager fm, List<Fragment> list) {
super(fm);
this.list = list;
}
@Override
public Fragment getItem(int position) {
return list.get(position);
}
@Override
public int getCount() {
return list.size();
}
}
指示器寬度佔螢幕三分之一,所以要先把 LayoutParams 改寫,再用位移動畫把它放回起始位置:
private void initCursorPosition() {
LayoutParams lp = viewIndicator.getLayoutParams();
lp.width = screenWidth / 3;
viewIndicator.setLayoutParams(lp);
TranslateAnimation animation = new TranslateAnimation(-screenWidth / 3, 0, 0, 0);
animation.setFillAfter(true);
viewIndicator.startAnimation(animation);
}
移動指示器、改變文字顏色、記錄目前索引。
private OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
@Override
public void onPageSelected(int index) {
translateAnimation(index);
changeTextColor(index);
currentIndex = index;
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
@Override
public void onPageScrollStateChanged(int arg0) { }
};
依「目前位置」與「目標位置」判斷移動方向與距離,再套用系統 translate 動畫:
private void translateAnimation(int index) {
TranslateAnimation animation = null;
switch (index) {
case 0: // 訂閱 -> 精選
animation = new TranslateAnimation(screenWidth / 3, 0, 0, 0);
break;
case 1:
if (0 == currentIndex) { // 精選 -> 訂閱
animation = new TranslateAnimation(0, screenWidth / 3, 0, 0);
} else if (2 == currentIndex) { // 發現 -> 訂閱
animation = new TranslateAnimation((screenWidth / 3) * 2,
screenWidth / 3, 0, 0);
}
break;
case 2: // 訂閱 -> 發現
animation = new TranslateAnimation(screenWidth / 3,
(screenWidth / 3) * 2, 0, 0);
break;
}
animation.setFillAfter(true);
animation.setDuration(300);
viewIndicator.startAnimation(animation);
}
private void getScreenSize(Activity context) {
DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
screenWidth = dm.widthPixels;
screenHeight = dm.heightPixels;
}
實務上建議把這個方法抽到工具類,不要留在 Activity 裡。
整體就是一個 ListView,頂部輪播充當 Header。輪播本身也是 ViewPager,原理與系列第一篇的啟動頁一致,再加一個定時器週期性切頁即可。
說明:範例中的圖片是寫死的,正式產品會由伺服器下發。
一個 ViewPager 加上承載指示點的 LinearLayout,外層固定高度 200dp。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="200dp">
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:id="@+id/tv_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="5dp"
android:text="公眾號:ansen_666" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/viewGroup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="5dp"
android:gravity="center_horizontal"
android:orientation="horizontal" />
</RelativeLayout>
</RelativeLayout>
</LinearLayout>
viewPager = (ViewPager) headView.findViewById(R.id.viewpager);
selectedPagerAdapter = new SelectedPagerAdapter(getActivity(), carousePagerSelectView);
viewPager.setOffscreenPageLimit(2);
viewPager.setCurrentItem(0);
viewPager.setOnPageChangeListener(onPageChangeListener);
viewPager.setAdapter(selectedPagerAdapter);
ViewGroup group = (ViewGroup) headView.findViewById(R.id.viewGroup);
tips = new ImageView[3];
for (int i = 0; i < tips.length; i++) {
ImageView imageView = new ImageView(getActivity());
if (i == 0) {
imageView.setBackgroundResource(R.drawable.page_indicator_focused);
} else {
imageView.setBackgroundResource(R.drawable.page_indicator_unfocused);
}
tips[i] = imageView;
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
lp.leftMargin = 10;
lp.rightMargin = 10;
group.addView(imageView, lp);
}
listView = (ListView) rootView.findViewById(R.id.list);
listView.addHeaderView(headView);
用 Timer 計時、Handler 更新 UI:
private Timer timer;
private final int CAROUSEL_TIME = 3000; // 3 秒換一頁
timer = new Timer(true);
timer.schedule(task, 0, CAROUSEL_TIME);
TimerTask task = new TimerTask() {
public void run() {
handler.sendEmptyMessage(CAROUSEL_TIME);
}
};
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case CAROUSEL_TIME:
if (currentIndex >= tips.length - 1) {
viewPager.setCurrentItem(0); // 回到第一頁
} else {
viewPager.setCurrentItem(currentIndex + 1);
}
break;
}
}
};
第一,Timer 內只做計時,UI 更新一律交給 Handler,這是因為 Timer 的執行緒不是主執行緒,直接改 View 會出錯。
第二,Activity 銷毀時務必 timer.cancel(),否則背景執行緒會持續發送訊息造成記憶體洩漏。另外提醒:ListView.addHeaderView() 必須在 setAdapter() 之前呼叫(API ใหม่版本雖已放寬,但保持這個習慣較安全),且同一個 View 不可重複 add,旋轉螢幕重建時要留意。
Android 源碼中的觀察者模式:以 Adapter 數據刷新為例
一、模式概述 定義 觀察者模式定義了對象之間的一種「一對多」依賴關係:當某一個對象的狀態發生改變時,所有依賴於它的對象都會收到通知,並被自動更新。 典型使用場景 關聯行
Android 自定義控件深入學習:生成隨機驗證碼
上一篇我們介紹了自定義控件的屬性(詳見《詳解 Android 自定義控件屬性 TypedArray 以及 attrs》)。在此基礎上,本文進一步實作一個隨機驗證碼生成控件
ListView 進階用法總整理:自訂版面、效能優化與單位換算
ListView 在 Android 開發中的使用頻率極高,值得花時間把它的完整用法與效能要點整理清楚。本文以 ListViewTest 專案為例,從最簡單的字串列表出發
Android 藍牙入門(一):基本概念與硬件接口
前言Android 藍牙系統涉及硬件、驅動、協議棧與應用層等多個層面。本文先從基本概念與硬件接口切入,說明 AP、BP、CP、RF 等常見名詞,並介紹藍牙模組常見的 UA