編輯:Android 開發實例
早年手機人人、朋友圈一類客戶端的側滑抽屜,就是這種交互的經典範例。系統並沒有現成的抽屜控件(直到後來的 DrawerLayout 出現),因此早期做法是自定義一個 ViewGroup,把「把手」和「內容」作為兩個子元素,透過手势控制位移。
核心思路有三點:自定義 Panel 容器;用 GestureDetector 識別拖動與快速滑動;用 TranslateAnimation 配合 canvas.translate() 完成開合動畫。同時用 declare-styleable 把方向、時長、把手背景等參數暴露到 XML 中,方便複用。
注意第二行的自定義命名空間必須與應用的包名一致,否則屬性無法解析:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:panel="https://schemas.android.com/apk/res/com.su.houses"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFFFF"
android:orientation="horizontal" >
<com.su.houses.panel.Panel
android:id="@+id/leftPanel1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
panel:closedHandle="@xml/left_switcher_collapsed_background"
panel:openedHandle="@xml/left_switcher_expanded_background"
panel:position="left" >
<Button
android:id="@+id/panelHandle"
android:layout_width="10dip"
android:layout_height="fill_parent" />
<!-- 下面是抽屜的布局 -->
<LinearLayout
android:id="@+id/panelContent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#999932"
android:gravity="center"
android:orientation="vertical" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button"
android:text="項目介紹" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button"
android:text="總體規劃" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button"
android:text="交通動線" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button"
android:text="生活配套" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button"
android:text="未來生活" />
</LinearLayout>
</com.su.houses.panel.Panel>
<ImageView
android:id="@+id/project_image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/dogs" />
</LinearLayout>
這裡有兩個約定:panelHandle 是拖動把手,panelContent 是抽屜內容。自定義 View 在 onFinishInflate() 中會去 findViewById 這兩個 id,找不到就直接拋異常,因此它們必須存在。
放在 res/values 目錄下,聲明抽屜可用的各項參數:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="Panel"> <!-- Defines panel animation duration in ms. --> <attr format="integer" name="animationDuration" /> <!-- Defines panel position on the screen. --> <attr name="position"> <!-- Panel placed at top of the screen. --> <enum name="top" value="0" /> <!-- Panel placed at bottom of the screen. --> <enum name="bottom" value="1" /> <!-- Panel placed at left of the screen. --> <enum name="left" value="2" /> <!-- Panel placed at right of the screen. --> <enum name="right" value="3" /> </attr> <!-- Defines if flying gesture forces linear interpolator in animation. --> <attr format="boolean" name="linearFlying" /> <!-- Defines opened handle (drawable/color). --> <attr format="reference|color" name="openedHandle" /> <!-- Defines closed handle (drawable/color). --> <attr format="reference|color" name="closedHandle" /> </declare-styleable> <item name="panelHandle" type="id"/> <item name="panelContent" type="id"/> </resources>
下面是一個精簡後但保留完整邏輯的實現,註釋保留了幾個容易踩坑的點:
package com.su.houses.panel;
import com.su.houses.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
public class Panel extends LinearLayout
{
/**
* Callback invoked when the panel is opened/closed.
*/
public static interface OnPanelListener
{
/** Invoked when the panel becomes fully closed. */
public void onPanelClosed(Panel panel);
/** Invoked when the panel becomes fully opened. */
public void onPanelOpened(Panel panel);
}
private boolean mIsShrinking; // 判斷是否是正在收縮狀態
private int mPosition;
private int mDuration;
private boolean mLinearFlying;
private View mHandle;
private View mContent;
private Drawable mOpenedHandle;
private Drawable mClosedHandle;
private float mTrackX; // X 方向上的拖動追蹤
private float mTrackY; // Y 方向上的拖動追蹤
private float mVelocity; // Fling 狀態每秒劃過的像素
private OnPanelListener panelListener;
public static final int TOP = 0;
public static final int BOTTOM = 1;
public static final int LEFT = 2;
public static final int RIGHT = 3;
private enum State
{
ABOUT_TO_ANIMATE, // 由 READY 進入這個狀態,但還沒有發生動畫、滾動和滑動
ANIMATING, // 正在動畫
READY, // 就緒狀態什麼都不做
TRACKING, // 拖動
FLYING, // 快速滑動
};
private State mState;
private Interpolator mInterpolator;
private GestureDetector mGestureDetector; // 手勢監聽器
private int mContentHeight;
private int mContentWidth;
private int mOrientation; // 動畫出現的方向
private PanelOnGestureListener mGestureListener; // 手勢監聽器的回調
public Panel(Context context, AttributeSet attrs)
{
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Panel);
mDuration = a.getInteger(R.styleable.Panel_animationDuration, 750);
mPosition = a.getInteger(R.styleable.Panel_position, BOTTOM);
mLinearFlying = a.getBoolean(R.styleable.Panel_linearFlying, false);
mOpenedHandle = a.getDrawable(R.styleable.Panel_openedHandle);
mClosedHandle = a.getDrawable(R.styleable.Panel_closedHandle);
a.recycle();
mOrientation = (mPosition == TOP || mPosition == BOTTOM) ? VERTICAL : HORIZONTAL;
setOrientation(mOrientation);
mState = State.READY;
mGestureListener = new PanelOnGestureListener();
mGestureDetector = new GestureDetector(mGestureListener);
mGestureDetector.setIsLongpressEnabled(false); // 長按沒有返回值所以去掉
}
public void setOnPanelListener(OnPanelListener onPanelListener)
{
panelListener = onPanelListener;
}
public View getHandle() { return mHandle; }
public View getContent() { return mContent; }
public void setInterpolator(Interpolator i) { mInterpolator = i; }
/**
* Set the opened state of Panel.
* @param open True if Panel is to be opened, false if it is to be closed.
* @param animate True if use animation, false otherwise.
*/
public void setOpen(boolean open, boolean animate)
{
if (isOpen() ^ open)
{
mIsShrinking = !open;
if (animate)
{
mState = State.ABOUT_TO_ANIMATE;
if (!mIsShrinking)
{
// this could make flicker so we test mState in dispatchDraw()
mContent.setVisibility(VISIBLE);
}
post(startAnimation);
}
else
{
mContent.setVisibility(open ? VISIBLE : GONE);
postProcess();
}
}
}
public boolean isOpen()
{
return mContent.getVisibility() == VISIBLE;
}
/* 在這裡完成 handle 與 Content 的初始化工作 */
@Override
protected void onFinishInflate()
{
super.onFinishInflate();
mHandle = findViewById(R.id.panelHandle);
if (mHandle == null)
{
throw new RuntimeException("Your Panel must have a View whose id attribute is 'R.id.panelHandle'");
}
mHandle.setOnTouchListener(touchListener);
mContent = findViewById(R.id.panelContent);
if (mContent == null)
{
throw new RuntimeException("Your Panel must have a View whose id attribute is 'R.id.panelContent'");
}
// reposition children
removeView(mHandle);
removeView(mContent);
if (mPosition == TOP || mPosition == LEFT)
{
addView(mContent);
addView(mHandle);
}
else
{
addView(mHandle);
addView(mContent);
}
if (mClosedHandle != null)
{
mHandle.setBackgroundDrawable(mClosedHandle);
}
mContent.setVisibility(GONE);
}
/* 獲取 Content 的寬高 */
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
super.onLayout(changed, l, t, r, b);
mContentWidth = mContent.getWidth();
mContentHeight = mContent.getHeight();
}
/* 根據控件的不同狀態修改畫布的偏移量 */
@Override
protected void dispatchDraw(Canvas canvas)
{
// 避免動畫開始前閃爍
if (mState == State.ABOUT_TO_ANIMATE && !mIsShrinking)
{
int delta = mOrientation == VERTICAL ? mContentHeight : mContentWidth;
if (mPosition == LEFT || mPosition == TOP)
{
delta = -delta;
}
if (mOrientation == VERTICAL)
{
canvas.translate(0, delta);
}
else
{
canvas.translate(delta, 0);
}
}
if (mState == State.TRACKING || mState == State.FLYING)
{
canvas.translate(mTrackX, mTrackY);
// translate 只改變繪製位置,不會觸發 layout(),
// 因此外部的觸摸事件仍按 translate 之前的坐標判定
}
super.dispatchDraw(canvas);
}
private float ensureRange(float v, int min, int max)
{
v = Math.max(v, min);
v = Math.min(v, max);
return v;
}
OnTouchListener touchListener = new OnTouchListener()
{
int initX;
int initY;
boolean setInitialPosition;
public boolean onTouch(View v, MotionEvent event)
{
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN)
{
initX = 0;
initY = 0;
if (mContent.getVisibility() == GONE)
{
// 此時還不知道 content 尺寸,先用因子表示
if (mOrientation == VERTICAL)
{
initY = mPosition == TOP ? -1 : 1;
}
else
{
initX = mPosition == LEFT ? -1 : 1;
}
}
setInitialPosition = true;
}
else
{
/*
* ACTION_DOWN 的操作都是根據 handle 的,Content 激活後重新 layout,
* handle 的位置發生了改變,而後續事件的坐標又是基於新的 handle 位置,
* 這樣就存在誤差,需要用 offsetLocation 修正過來。
*/
if (setInitialPosition)
{
initX *= mContentWidth;
initY *= mContentHeight;
mGestureListener.setScroll(initX, initY);
setInitialPosition = false;
// offsetLocation 需要取反
initX = -initX;
initY = -initY;
}
// 如果去掉這一句,開始拖動不響應,拖動一段距離後才能拉出 Content
event.offsetLocation(initX, initY);
}
boolean result = mGestureDetector.onTouchEvent(event);
if (!result)
{
if (action == MotionEvent.ACTION_UP)
{
// tup up after scrolling
post(startAnimation);
}
}
return false;
}
};
Runnable startAnimation = new Runnable()
{
public void run()
{
TranslateAnimation animation;
int fromXDelta = 0, toXDelta = 0, fromYDelta = 0, toYDelta = 0;
if (mState == State.FLYING)
{
mIsShrinking = (mPosition == TOP || mPosition == LEFT) ^ (mVelocity > 0);
}
int calculatedDuration;
if (mOrientation == VERTICAL)
{
int height = mContentHeight;
if (!mIsShrinking) { fromYDelta = mPosition == TOP ? -height : height; }
else { toYDelta = mPosition == TOP ? -height : height; }
if (mState == State.TRACKING)
{
if (Math.abs(mTrackY - fromYDelta) < Math.abs(mTrackY - toYDelta))
{
mIsShrinking = !mIsShrinking;
toYDelta = fromYDelta;
}
fromYDelta = (int) mTrackY;
}
else if (mState == State.FLYING)
{
fromYDelta = (int) mTrackY;
}
if (mState == State.FLYING && mLinearFlying)
{
calculatedDuration = (int) (1000 * Math.abs((toYDelta - fromYDelta) / mVelocity));
calculatedDuration = Math.max(calculatedDuration, 20);
}
else
{
calculatedDuration = mDuration * Math.abs(toYDelta - fromYDelta) / mContentHeight;
}
}
else
{
int width = mContentWidth;
if (!mIsShrinking) { fromXDelta = mPosition == LEFT ? -width : width; }
else { toXDelta = mPosition == LEFT ? -width : width; }
if (mState == State.TRACKING)
{
if (Math.abs(mTrackX - fromXDelta) < Math.abs(mTrackX - toXDelta))
{
mIsShrinking = !mIsShrinking;
toXDelta = fromXDelta;
}
fromXDelta = (int) mTrackX;
}
else if (mState == State.FLYING)
{
fromXDelta = (int) mTrackX;
}
if (mState == State.FLYING && mLinearFlying)
{
calculatedDuration = (int) (1000 * Math.abs((toXDelta - fromXDelta) / mVelocity));
calculatedDuration = Math.max(calculatedDuration, 20);
}
else
{
calculatedDuration = mDuration * Math.abs(toXDelta - fromXDelta) / mContentWidth;
}
}
mTrackX = mTrackY = 0;
if (calculatedDuration == 0)
{
mState = State.READY;
if (mIsShrinking) { mContent.setVisibility(GONE); }
postProcess();
return;
}
animation = new TranslateAnimation(fromXDelta, toXDelta, fromYDelta, toYDelta);
animation.setDuration(calculatedDuration);
animation.setAnimationListener(animationListener);
if (mState == State.FLYING && mLinearFlying)
{
animation.setInterpolator(new LinearInterpolator());
}
else if (mInterpolator != null)
{
animation.setInterpolator(mInterpolator);
}
startAnimation(animation);
}
};
private AnimationListener animationListener = new AnimationListener()
{
public void onAnimationEnd(Animation animation)
{
mState = State.READY;
if (mIsShrinking) { mContent.setVisibility(GONE); }
postProcess();
}
public void onAnimationRepeat(Animation animation) { }
public void onAnimationStart(Animation animation)
{
mState = State.ANIMATING;
}
};
/** 處理把手的背景切換,並回調監聽器 */
private void postProcess()
{
if (mIsShrinking && mClosedHandle != null)
{
mHandle.setBackgroundDrawable(mClosedHandle);
}
else if (!mIsShrinking && mOpenedHandle != null)
{
mHandle.setBackgroundDrawable(mOpenedHandle);
}
if (panelListener != null)
{
if (mIsShrinking) { panelListener.onPanelClosed(Panel.this); }
else { panelListener.onPanelOpened(Panel.this); }
}
}
class PanelOnGestureListener implements OnGestureListener
{
float scrollY;
float scrollX;
public void setScroll(int initScrollX, int initScrollY)
{
scrollX = initScrollX;
scrollY = initScrollY;
}
public boolean onDown(MotionEvent e)
{
scrollX = scrollY = 0;
if (mState != State.READY)
{
// 正在動畫或即將動畫,忽略新的按下
return false;
}
mState = State.ABOUT_TO_ANIMATE;
mIsShrinking = mContent.getVisibility() == VISIBLE;
if (!mIsShrinking)
{
mContent.setVisibility(VISIBLE);
}
return true;
}
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
mState = State.FLYING;
mVelocity = mOrientation == VERTICAL ? velocityY : velocityX;
post(startAnimation);
return true;
}
public void onLongPress(MotionEvent e) { }
/** 更新 mTrackX / mTrackY,觸發重繪 */
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
{
mState = State.TRACKING;
float tmpY = 0, tmpX = 0;
if (mOrientation == VERTICAL)
{
scrollY -= distanceY;
if (mPosition == TOP) { tmpY = ensureRange(scrollY, -mContentHeight, 0); }
else { tmpY = ensureRange(scrollY, 0, mContentHeight); }
}
else
{
scrollX -= distanceX;
if (mPosition == LEFT) { tmpX = ensureRange(scrollX, -mContentWidth, 0); }
else { tmpX = ensureRange(scrollX, 0, mContentWidth); }
}
if (tmpX != mTrackX || tmpY != mTrackY)
{
mTrackX = tmpX;
mTrackY = tmpY;
invalidate();
}
return true;
}
public void onShowPress(MotionEvent e) { }
public boolean onSingleTapUp(MotionEvent e)
{
// simple tap: 直接切換開合
post(startAnimation);
return true;
}
}
}
left_switcher_collapsed_background.xml 只是一個普通的 selector,用於切換把手在不同狀態下的圖形:
<selector xmlns:android="https://schemas.android.com/apk/res/android"> <item android:state_window_focused="false" android:state_pressed="false" android:drawable="@drawable/notes_button" /> <item android:state_window_focused="true" android:state_pressed="true" android:drawable="@drawable/notes_button" /> <item android:state_focused="true" android:drawable="@drawable/notes_button" /> </selector>
1. 讓控件水平或垂直居中:不必給子元素設置 layout_gravity,只要在它的上一級容器上寫 android:gravity="center" 即可。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:gravity="center" android:background="#000000" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageView android:id="@+id/logo" android:src="@drawable/logo" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
2. 全局全屏:直接在 application 上設置主題,省去逐個 Activity 配置的麻煩。
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" android:screenOrientation="landscape" >
3. 單個 Activity 鎖定橫屏:
<activity android:label="@string/app_name" android:name=".HousesActivity" android:screenOrientation="landscape">
需要補充的是,這套自定義 Panel 的方案在當年很有代表性,但存在幾個明顯短板:它把抽屜直接塞進 Activity 的布局樹,無法跨 Activity 復用;手勢判定依賴 translate 造成的視覺位移,事件坐標系統並未同步,這正是代碼裡需要 offsetLocation 修正的根因;此外它沒有遮罩層,抽屜打開時主內容依然可點擊。在現代開發中,直接使用 DrawerLayout 配合 ActionBarDrawerToggle 是更省事也更符合規範的選擇。
Android 進度 Spinner 使用指南:從 XML 到 Java 控制
Android 的載入 Spinner 常用於「不知道還要等多久」的情境。它不需要精確百分比,只用旋轉動畫提醒使用者目前有任務正在進行。 加入元件 在 XML 中加入 P
Android 音訊播放器開發:MediaPlayer 控制播放進度
Android 的 MediaPlayer 類別可播放音訊與影片。開發時常用來製作音樂播放器、朗讀器或簡單的多媒體展示。 建立與播放 可透過 create 方法載入 ra
Android 進階:TelephonyManager 功能探秘
前文介紹了如何用 Java 反射機制調用藍牙的隱藏 API,本文繼續拿反射機制練手,探秘 TelephonyManager 在 Framework 中存在、卻在 SDK
Android 簡易音樂播放器實作:從介面到背景播放
這篇文章整理一個適合入門的 Android 音樂播放器範例,重點在於把播放控制交給背景 Service,再透過 Binder 讓 Activity 與 Service