編輯:Android 開發實例
「頂部標簽 + 下方 ViewPager」是很常見的交互,難點在於兩件事:標簽的下標 indicator 要能跟著滑動,標簽太多時整個標簽欄要能橫向滾動。本文封裝一個 SyncHorizontalScrollView 把這兩件事一起解決。
package com.example.playtabtest.view;
import com.example.playtabtest.R;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class SyncHorizontalScrollView extends HorizontalScrollView {
private View view;
private ImageView leftImage;
private ImageView rightImage;
private int windowWitdh = 0;
private Activity mContext;
private RadioGroup rg_nav_content;
private ImageView iv_nav_indicator;
private LayoutInflater mInflater;
private int indicatorWidth; // 每個標簽所占的寬度
private int currentIndicatorLeft = 0; // 當前 indicator 的位移
private ViewPager mViewPager; // 與本 view 關聯的 ViewPager
public SyncHorizontalScrollView(Context context) {
super(context);
}
public SyncHorizontalScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* 綁定關聯的 ViewPager 與外圍控件
*
* @param mViewPager 與本 view 關聯的 ViewPager
* @param leftImage 左箭頭
* @param rightImage 右箭頭
* @param tabTitle 標簽名稱數組
* @param count 一屏顯示的標簽數
* @param context
*/
public void setSomeParam(ViewPager mViewPager, ImageView leftImage,
ImageView rightImage, String[] tabTitle, int count, Activity context) {
this.mContext = context;
this.mViewPager = mViewPager;
mInflater = LayoutInflater.from(context);
this.view = mInflater.inflate(R.layout.sync_hsv_item, null);
this.addView(view);
this.leftImage = leftImage;
this.rightImage = rightImage;
DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
windowWitdh = dm.widthPixels;
indicatorWidth = windowWitdh / count;
init(tabTitle);
this.invalidate();
}
private void init(String[] tabTitle) {
rg_nav_content = (RadioGroup) view.findViewById(R.id.rg_nav_content);
iv_nav_indicator = (ImageView) view.findViewById(R.id.iv_nav_indicator);
initIndicatorWidth();
initNavigationHSV(tabTitle);
setListener();
}
/** 設置 indicator 的寬度,與單個標簽等寬 */
private void initIndicatorWidth() {
ViewGroup.LayoutParams cursor_Params = iv_nav_indicator.getLayoutParams();
cursor_Params.width = indicatorWidth;
iv_nav_indicator.setLayoutParams(cursor_Params);
}
/** 動態添加頂部標簽 */
private void initNavigationHSV(String[] tabTitle) {
rg_nav_content.removeAllViews();
for (int i = 0; i < tabTitle.length; i++) {
RadioButton rb = (RadioButton) mInflater.inflate(
R.layout.nav_radiogroup_item, null);
rb.setId(i);
rb.setText(tabTitle[i]);
rb.setLayoutParams(new LayoutParams(indicatorWidth,
LayoutParams.MATCH_PARENT));
rg_nav_content.addView(rb);
}
}
private void setListener() {
rg_nav_content.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (rg_nav_content.getChildAt(checkedId) != null) {
// 讓 indicator 從當前位置移動到目標標簽
TranslateAnimation animation = new TranslateAnimation(
currentIndicatorLeft,
((RadioButton) rg_nav_content.getChildAt(checkedId)).getLeft(),
0f, 0f);
animation.setInterpolator(new LinearInterpolator());
animation.setDuration(100);
animation.setFillAfter(true);
iv_nav_indicator.startAnimation(animation);
// ViewPager 跟隨切換
mViewPager.setCurrentItem(checkedId);
// 記錄 indicator 距離最左側的距離
currentIndicatorLeft = ((RadioButton) rg_nav_content
.getChildAt(checkedId)).getLeft();
// 讓被選中的標簽滾到可视範圍內
smoothScrollTo(
(checkedId > 1
? ((RadioButton) rg_nav_content.getChildAt(checkedId)).getLeft()
: 0)
- ((RadioButton) rg_nav_content.getChildAt(2)).getLeft(),
0);
}
}
});
}
/** 模擬點擊,供外部(例如 ViewPager 翻頁後)調用 */
public void performLabelClick(int position) {
if (rg_nav_content != null && rg_nav_content.getChildCount() > position) {
((RadioButton) rg_nav_content.getChildAt(position)).performClick();
}
}
/** 根據滾動位置決定左右箭頭的顯示與隱藏 */
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (!mContext.isFinishing() && view != null
&& rightImage != null && leftImage != null) {
if (view.getWidth() <= windowWitdh) {
// 內容不足一屏,箭頭都隱藏
leftImage.setVisibility(View.GONE);
rightImage.setVisibility(View.GONE);
} else {
if (l == 0) {
leftImage.setVisibility(View.GONE);
rightImage.setVisibility(View.VISIBLE);
} else if (view.getWidth() - l == windowWitdh) {
leftImage.setVisibility(View.VISIBLE);
rightImage.setVisibility(View.GONE);
} else {
leftImage.setVisibility(View.VISIBLE);
rightImage.setVisibility(View.VISIBLE);
}
}
}
}
}
用 RadioGroup 承載標簽是為了直接複用它的單選能力,indicator 則是覆蓋在 RadioGroup 下方的一個色塊。
<?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" >
<RelativeLayout
android:id="@+id/rl_nav"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#5AB0EB" >
<RadioGroup
android:id="@+id/rg_nav_content"
android:layout_width="fill_parent"
android:layout_height="38dip"
android:layout_alignParentTop="true"
android:background="#F2F2F2"
android:orientation="horizontal" >
</RadioGroup>
<ImageView
android:id="@+id/iv_nav_indicator"
android:layout_width="1dip"
android:layout_height="5dip"
android:layout_alignParentBottom="true"
android:background="#5AB0EB"
android:contentDescription="@string/nav_desc"
android:scaleType="matrix" />
</RelativeLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RadioButton xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:background="#F2F2F2"
android:button="@null"
android:checked="true"
android:gravity="center"
android:text=""
android:textColor="@drawable/rb_blue_bg"
android:textSize="14.0dip" />
android:button="@null" 是為了去掉 RadioButton 默認的小圓點,只保留文字切換效果。
上面只處理了「點標簽 → ViewPager 切頁」這一半。另一半要在 Activity 裡給 ViewPager 設置 OnPageChangeListener,在 onPageSelected 中調用 performLabelClick(position)。這樣做的好處是 indicator 動畫、標簽滾動的邏輯全部集中在自定義 View 內部,Activity 只需要做一行轉發,滑動和點擊兩個方向自然就同步了。
另外 smoothScrollTo 裡減去 getChildAt(2).getLeft() 是一個讓選中項盡量居中顯示的偏移技巧,具體的基準位置可以根據自己的標簽寬度和數量微調。
Android 載入 Spinner 進度指示實作
在 Android 裡,當某項工作正在進行、想讓使用者知道「系統還在忙」,就可以用進度條來表達。進度條大致有兩種形式:帶有進度的水平進度列,以及持續旋轉的載入轉圈(Spi
Android 開發自學筆記(五):用程式碼把版面串成真正的功能
好看的骨架已經有了,接下來要讓它真正動起來。只有外表、沒有內涵的花拳繡腿可不行。 從前面幾篇,我們已經能把版面搭成這個樣子: 相關文章:Android 自學開發第四篇之
Android 載入 Spinner 進度條實作教學
在 Android 中,可以透過進度條來向使用者顯示某項任務的執行進展。進度條主要分為兩種形態:進度列與旋轉式載入指示器(Spinner)。本章將聚焦於後者。 Spinn
Android手機衛士(十七):用自訂屬性擴充設定項
前面已完成設定中心第一欄,接下來要讓其他設定欄也能重複使用。做法是為自訂 SettingItemView 宣告可配置屬性。宣告自訂屬性在 res/values/attrs