Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

自訂 ViewGroup 實作類 Launcher 橫向滑屏:Scroller 與 VelocityTracker 應用

編輯:Android 開發實例

手機桌面那種「手指一掃、畫面整頁滑過去並自動吸附」的效果,是很多引導頁、相簿、卡片式介面的標準互動。要自己做出來,需要三個零件:一個自訂 ViewGroup 負責排列與攔截觸控、Scroller 負責補間動畫、VelocityTracker 負責判斷使用者是「慢慢拖」還是「快速甩」。

核心邏輯是:ACTION_MOVE 時跟著手指 scrollBy(),ACTION_UP 時看速度決定要停在當前頁、前一頁還是後一頁,最後交給 Scroller 做平滑收尾。

MyScrollLayout

public class MyScrollLayout extends ViewGroup{

private VelocityTracker mVelocityTracker; // 用於判斷甩動手勢

private static final int SNAP_VELOCITY = 600;

private Scroller mScroller; // 滑動控制器

private int mCurScreen;

private int mDefaultScreen = 0;

private float mLastMotionX;

private OnViewChangeListener mOnViewChangeListener;

public MyScrollLayout(Context context) {

super(context);

init(context);

}

public MyScrollLayout(Context context, AttributeSet attrs) {

super(context, attrs);

init(context);

}

public MyScrollLayout(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

init(context);

}

private void init(Context context)

{

mCurScreen = mDefaultScreen;

mScroller = new Scroller(context);

}

@Override

protected void onLayout(boolean changed, int l, int t, int r, int b) {

if (changed) {

int childLeft = 0;

final int childCount = getChildCount();

for (int i=0; i<childCount; i++) {

final View childView = getChildAt(i);

if (childView.getVisibility() != View.GONE) {

final int childWidth = childView.getMeasuredWidth();

childView.layout(childLeft, 0,

childLeft+childWidth, childView.getMeasuredHeight());

childLeft += childWidth;

}

}

}

}

@Override

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

super.onMeasure(widthMeasureSpec, heightMeasureSpec);

final int width = MeasureSpec.getSize(widthMeasureSpec);

final int widthMode = MeasureSpec.getMode(widthMeasureSpec);

final int count = getChildCount();

for (int i = 0; i < count; i++) {

getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);

}

scrollTo(mCurScreen * width, 0);

}

public void snapToDestination() {

final int screenWidth = getWidth();

final int destScreen = (getScrollX()+ screenWidth/2)/screenWidth;

snapToScreen(destScreen);

}

public void snapToScreen(int whichScreen) {

whichScreen = Math.max(0, Math.min(whichScreen, getChildCount()-1));

if (getScrollX() != (whichScreen*getWidth())) {

final int delta = whichScreen*getWidth()-getScrollX();

mScroller.startScroll(getScrollX(), 0,

delta, 0, Math.abs(delta)*2);

mCurScreen = whichScreen;

invalidate(); // Redraw the layout

if (mOnViewChangeListener != null)

{

mOnViewChangeListener.OnViewChange(mCurScreen);

}

}

}

@Override

public void computeScroll() {

if (mScroller.computeScrollOffset()) {

scrollTo(mScroller.getCurrX(), mScroller.getCurrY());

postInvalidate();

}

}

@Override

public boolean onTouchEvent(MotionEvent event) {

final int action = event.getAction();

final float x = event.getX();

final float y = event.getY();

switch (action) {

case MotionEvent.ACTION_DOWN:

Log.i("", "onTouchEvent ACTION_DOWN");

if (mVelocityTracker == null) {

mVelocityTracker = VelocityTracker.obtain();

mVelocityTracker.addMovement(event);

}

if (!mScroller.isFinished()){

mScroller.abortAnimation();

}

mLastMotionX = x;

break;

case MotionEvent.ACTION_MOVE:

int deltaX = (int)(mLastMotionX - x);

if (IsCanMove(deltaX))

{

if (mVelocityTracker != null)

{

mVelocityTracker.addMovement(event);

}

mLastMotionX = x;

scrollBy(deltaX, 0);

}

break;

case MotionEvent.ACTION_UP:

int velocityX = 0;

if (mVelocityTracker != null)

{

mVelocityTracker.addMovement(event);

mVelocityTracker.computeCurrentVelocity(1000);

velocityX = (int) mVelocityTracker.getXVelocity();

}

if (velocityX > SNAP_VELOCITY && mCurScreen > 0) {

// Fling enough to move left

snapToScreen(mCurScreen - 1);

} else if (velocityX < -SNAP_VELOCITY

&& mCurScreen < getChildCount() - 1) {

// Fling enough to move right

snapToScreen(mCurScreen + 1);

} else {

snapToDestination();

}

if (mVelocityTracker != null) {

mVelocityTracker.recycle();

mVelocityTracker = null;

}

break;

}

return true;

}

private boolean IsCanMove(int deltaX)

{

if (getScrollX() <= 0 && deltaX < 0 ){

return false;

}

if (getScrollX() >= (getChildCount() - 1) * getWidth() && deltaX > 0){

return false;

}

return true;

}

public void SetOnViewChangeListener(OnViewChangeListener listener)

{

mOnViewChangeListener = listener;

}

}

幾個細節值得留意。onMeasure() 讓每個子 View 都量測成「一整屏」,並在最後用 scrollTo 回到當前頁,避免旋轉螢幕後位置跑掉。computeScroll() 是 Scroller 動畫的驅動核心,必須在裡頭呼叫 postInvalidate() 才能持續刷新。IsCanMove() 則負責邊界攔截,讓第一頁無法再往右拖、最後頁無法再往左拖。VelocityTracker 用完務必 recycle(),這是常被忽略的記憶體責任。

Activity:加上頁碼指示點

public class SwitchViewDemoActivity extends Activity implements OnViewChangeListener, OnClickListener{

private MyScrollLayout mScrollLayout;

private ImageView[] mImageViews;

private int mViewCount;

private int mCurSel;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

init();

}

private void init()

{

mScrollLayout = (MyScrollLayout) findViewById(R.id.ScrollLayout);

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.llayout);

//動態添加一個layout控件

LinearLayout layout=new LinearLayout(this);

layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));

layout.setBackgroundResource(R.drawable.guide01);

mScrollLayout.addView(layout);

//動態添加一個imageView控件

ImageView imageView=new ImageView(this);

imageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

imageView.setPadding(15, 15, 15, 15);

imageView.setImageResource(R.drawable.guide_round);

linearLayout.addView(imageView);

mViewCount = mScrollLayout.getChildCount();

mImageViews = new ImageView[mViewCount];

for(int i = 0; i < mViewCount; i++) {

mImageViews[i] = (ImageView) linearLayout.getChildAt(i);

mImageViews[i].setEnabled(true);

mImageViews[i].setOnClickListener(this);

mImageViews[i].setTag(i);

}

mCurSel = 0;

mImageViews[mCurSel].setEnabled(false);

mScrollLayout.SetOnViewChangeListener(this);

}

private void setCurPoint(int index)

{

if (index < 0 || index > mViewCount - 1 || mCurSel == index) {

return ;

}

mImageViews[mCurSel].setEnabled(true);

mImageViews[index].setEnabled(false);

mCurSel = index;

}

@Override

public void OnViewChange(int view) {

setCurPoint(view);

}

@Override

public void onClick(View v) {

int pos = (Integer)(v.getTag());

setCurPoint(pos);

mScrollLayout.snapToScreen(pos);

}

}

頁碼指示點的做法很巧妙:用 setEnabled(true/false) 切換 ImageView 的狀態,再搭配 selector 讓「當前頁」換成另一張圖,不必額外管理圖片資源。而 OnViewChangeListener 則讓滑動與點擊雙向同步——滑動時更新圓點,點圓點時呼叫 snapToScreen() 跳頁。

版面配置

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent" >

<cn.com.karl.scroll.MyScrollLayout

xmlns:android="https://schemas.android.com/apk/res/android"

android:id="@+id/ScrollLayout"

android:layout_width="fill_parent"

android:layout_height="fill_parent" >

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:background="@drawable/guide01" >

</LinearLayout>

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:background="@drawable/guide02" >

</LinearLayout>

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:background="@drawable/guide03" >

</LinearLayout>

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:background="@drawable/guide04" >

</LinearLayout>

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:background="@drawable/guide05" >

</LinearLayout>

</cn.com.karl.scroll.MyScrollLayout>

<LinearLayout

android:id="@+id/llayout"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentBottom="true"

android:layout_centerHorizontal="true"

android:layout_marginBottom="24.0dip"

android:orientation="horizontal" >

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center_vertical"

android:clickable="true"

android:padding="15.0dip"

android:src="@drawable/guide_round" />

(其餘四個 ImageView 設定相同)

</LinearLayout>

</RelativeLayout>

用 RelativeLayout 當外層是刻意的:MyScrollLayout 填滿整個畫面,頁碼列則用 alignParentBottom 與 centerHorizontal 疊在下方,兩者互不影響。若把自訂 ViewGroup 的類別名稱寫成完整路徑(cn.com.karl.scroll.MyScrollLayout)放在 XML 裡,Android 會自動將它實例化,這也是自訂控制項最方便的接入方式。

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