Android基于ViewFlipper实现图片切换
扫描二维码
随时随地手机看文章
在很多App上我们经常看到这些效果:
淘宝首页自动滚动的图片展示效果支付宝应用第一次启动启动的用户引导画面
要实现这些效果,有些控件可以帮助我们:
1. ViewPager
2. ViewFlipper
3. Fragment
好吧,我最终选择了ViewFlipper,因为它的使用最干劲清爽(往里面放几个View就行了),而且还支持自动播放。
不过,为了实现上面两个效果,还得解决来年两个问题:
1. 如何在ViewFlipper滚动的时候,获得当前展示的child id?
2. 和ViewPager原生支持触摸滑动翻页不同,ViewFlipper需要自己监听手势来解决。
问题1:其实,我挺奇怪的,Google既然为ViewAnimation做了个ViewFlipper的子类来支持自动翻滚,怎么不给它添加一个listener以监听翻滚事件呢?
好吧,既然google不给,那就自己加。首先看ViewFlipper的源码(
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.widget; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.TypedArray; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.util.Log; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.RemoteViews.RemoteView; /** * Simple {@link ViewAnimator} that will animate between two or more views * that have been added to it. Only one child is shown at a time. If * requested, can automatically flip between each child at a regular interval. * * @attr ref android.R.styleable#ViewFlipper_flipInterval * @attr ref android.R.styleable#ViewFlipper_autoStart */ @RemoteView public class ViewFlipper extends ViewAnimator { private static final String TAG = "ViewFlipper"; private static final boolean LOGD = false; private static final int DEFAULT_INTERVAL = 3000; private int mFlipInterval = DEFAULT_INTERVAL; private boolean mAutoStart = false; private boolean mRunning = false; private boolean mStarted = false; private boolean mVisible = false; private boolean mUserPresent = true; public ViewFlipper(Context context) { super(context); } public ViewFlipper(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.ViewFlipper); mFlipInterval = a.getInt( com.android.internal.R.styleable.ViewFlipper_flipInterval, DEFAULT_INTERVAL); mAutoStart = a.getBoolean( com.android.internal.R.styleable.ViewFlipper_autoStart, false); a.recycle(); } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (Intent.ACTION_SCREEN_OFF.equals(action)) { mUserPresent = false; updateRunning(); } else if (Intent.ACTION_USER_PRESENT.equals(action)) { mUserPresent = true; updateRunning(false); } } }; @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); // Listen for broadcasts related to user-presence final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_USER_PRESENT); getContext().registerReceiver(mReceiver, filter); if (mAutoStart) { // Automatically start when requested startFlipping(); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mVisible = false; getContext().unregisterReceiver(mReceiver); updateRunning(); } @Override protected void onWindowVisibilityChanged(int visibility) { super.onWindowVisibilityChanged(visibility); mVisible = visibility == VISIBLE; updateRunning(false); } /** * How long to wait before flipping to the next view * * @param milliseconds * time in milliseconds */ @android.view.RemotableViewMethod public void setFlipInterval(int milliseconds) { mFlipInterval = milliseconds; } /** * Start a timer to cycle through child views */ public void startFlipping() { mStarted = true; updateRunning(); } /** * No more flips */ public void stopFlipping() { mStarted = false; updateRunning(); } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setClassName(ViewFlipper.class.getName()); } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setClassName(ViewFlipper.class.getName()); } /** * Internal method to start or stop dispatching flip {@link Message} based * on {@link #mRunning} and {@link #mVisible} state. */ private void updateRunning() { updateRunning(true); } /** * Internal method to start or stop dispatching flip {@link Message} based * on {@link #mRunning} and {@link #mVisible} state. * * @param flipNow Determines whether or not to execute the animation now, in * addition to queuing future flips. If omitted, defaults to * true. */ private void updateRunning(boolean flipNow) { boolean running = mVisible && mStarted && mUserPresent; if (running != mRunning) { if (running) { showOnly(mWhichChild, flipNow); Message msg = mHandler.obtainMessage(FLIP_MSG); mHandler.sendMessageDelayed(msg, mFlipInterval); } else { mHandler.removeMessages(FLIP_MSG); } mRunning = running; } if (LOGD) { Log.d(TAG, "updateRunning() mVisible=" + mVisible + ", mStarted=" + mStarted + ", mUserPresent=" + mUserPresent + ", mRunning=" + mRunning); } } /** * Returns true if the child views are flipping. */ public boolean isFlipping() { return mStarted; } /** * Set if this view automatically calls {@link #startFlipping()} when it * becomes attached to a window. */ public void setAutoStart(boolean autoStart) { mAutoStart = autoStart; } /** * Returns true if this view automatically calls {@link #startFlipping()} * when it becomes attached to a window. */ public boolean isAutoStart() { return mAutoStart; } private final int FLIP_MSG = 1; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == FLIP_MSG) { if (mRunning) { showNext(); msg = obtainMessage(FLIP_MSG); sendMessageDelayed(msg, mFlipInterval); } } } }; }
代码还是挺简单易懂的,就是用了一个Handler来定时调用showNext()。
可惜,mHandler成员是private+final的,我们无法改动它了。
不过,既然ViewFlipper不是一个final类,那就好办,自定义类继承ViewFlipper,重载showNext()函数:
package com.example.viewflipper; import android.widget.ViewFlipper; /** * Created by ray on 7/4/13. */ public class MyViewFilpper extends ViewFlipper { private OnDisplayChagnedListener mListener; public MyViewFilpper(android.content.Context context) { super(context); } public MyViewFilpper(android.content.Context context, android.util.AttributeSet attrs) { super(context, attrs); } public void setOnDisplayChagnedListener(OnDisplayChagnedListener listener) { if (mListener != listener) { this.mListener = listener; } } @Override public void showNext() { super.showNext(); if(mListener != null){ mListener.OnDisplayChildChanging(this, super.getDisplayedChild()); } } @Override public void showPrevious() { super.showPrevious(); if(mListener != null){ mListener.OnDisplayChildChanging(this, super.getDisplayedChild()); } } public interface OnDisplayChagnedListener { void OnDisplayChildChanging(ViewFlipper view, int index); } }
问题2,就比较好解决了,OnTouchListener + GestureDetector 监听flipper事件,这里就不贴代码了。
好吧,这样基本问题都被解决了,为了让效果好一点,又给ViewFlipper加上了进入动画和离开动画。
好吧,下方的1,2,3有点难看,大家凑合下。
当目前为止,本人对效果还算满意,但是,还存在两个问题:
1. 没有处理GestureDetectorListener的onScroll函数,也就是说,在用户的手指离开屏幕前,不会有滚动效果。
2. 因为是通GestureDetector是通过TouchListener工作的,作为一个容器,如果内部元素消耗掉了touch事件,则touchlistener无法工作,手势的监听自然也无从谈起。不过,仅仅是应付图片浏览的话,还是有办法解决的:
a. 对于用户引导这样的场景,图片展示是不会消耗touch消息的。
b. 而淘宝首页的图片动态则不同,在用户点击图片的时候,把页面转到商品的展示页面,这种情况下,一般会考虑使用ImageButton控件来处理Click事件,这样就导致手势无法监听。解决方案是,仍旧使用ImageVIew控件,但是在GestureListener的OnSingleTapUp事件上,获取当前展示的页面,然后根据页面信息转到商品展示页面。
但是,如果是一些比较复杂的情况,就比较难处理,虽然通过重载onInterceptTouchEvent函数,父容器也能监听所有由子控件消耗的消息,但是也可能存在一些逻辑问题:例如在ViewFlipper容器内包含了一个Gallary控件,那scroll消息应该由哪个控件来处理,亦或都处理?这就是个比较费脑筋的问题了,设计UI的时候,可以考虑设计的简单些。