给大家拜个早年,今天做一个简单的卡片滑动,我发现魅族应用商店的应用详情都是以滑动的形式展示(感觉不好)。
动漫角色小应用:
简单思考:
- 动漫角色卡片为一个布局(可根据自己需要进行修改)
- 封装一个负责对布局进行滑动的工具类
- 在工具类中实现滑动及动画
卡片布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/card"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="@dimen/activity_horizontal_margin"
android:layout_marginRight="@dimen/activity_horizontal_margin"
android:layout_marginTop="40dp"
android:orientation="vertical"
tools:showIn="@layout/activity_main">
<android.support.v7.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardCornerRadius="10dp">
<ImageView
android:id="@+id/card_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:scaleType="centerCrop" />
</android.support.v7.widget.CardView>
</LinearLayout>
封装滑动工具类
在滑动动漫卡片时候,为了更好的体验我们在卡片范围内设置一个滑动的区域,超过这个区域就不做滑动,如上图红色范围是可以滑动区域。
public class SlideHelper implements View.OnTouchListener,
ValueAnimator.AnimatorUpdateListener{
private View view;
private float maxTouchable;
//判断卡片是否滑动
private boolean isSlide = true;
private float density;
private float viewHeight;
public SlideHelper(final View view) {
this.view = view;
this.density = view.getResources().getDisplayMetrics().density;
//设置卡片滑动区域大小
this.maxTouchable = 300 * density;
//监听onTouch事件
view.setOnTouchListener(this);
//创建动画
createAnimation();
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (ishind) {
viewHeight = view.getHeight();
hide();
}
//测量完毕移除掉(防止多次调用) view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
}
布局默认是显示,我需要把布局进行隐藏。
public class SlideHelper implements View.OnTouchListener,
ValueAnimator.AnimatorUpdateListener{
//隐藏布局
public void hide() {
if (view.getHeight() > 0) {
//让布局移动到Y轴指定像素
view.setTranslationY(viewHeight);
view.setVisibility(View.GONE);
} else {
ishind = true;
}
}
}
小知识点:
为什么用view.getViewTreeObserver().addOnGlobalLayoutListener()获取高度?
因为View的measure过程和Activity的生命周期不是同步执行的,因此无法保证Activity执行了生命周期方法时View已经测量完毕了,如果View没有测量完毕,那么获得的宽高就是0。(具体源码不分析,不是本篇的重点)
view.getViewTreeObserver().addOnGlobalLayoutListener()源码很简单。
class View{
public ViewTreeObserver getViewTreeObserver() {
if (mAttachInfo != null) {
return mAttachInfo.mTreeObserver;
}
if (mFloatingTreeObserver == null) {
mFloatingTreeObserver = new ViewTreeObserver();
}
return mFloatingTreeObserver;
}
}
ViewTreeObserver源码
class ViewTreeObserver{
public void addOnGlobalLayoutListener(OnGlobalLayoutListener listener) {
checkIsAlive();
if (mOnGlobalLayoutListeners == null) {
mOnGlobalLayoutListeners = new CopyOnWriteArray<OnGlobalLayoutListener>();
}
mOnGlobalLayoutListeners.add(listener);
}
public final void dispatchOnGlobalLayout() {
// NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
// perform the dispatching. The iterator is a safe guard against listeners that
// could mutate the list by calling the various add/remove methods. This prevents
// the array from being modified while we iterate it.
final CopyOnWriteArray<OnGlobalLayoutListener> listeners = mOnGlobalLayoutListeners;
if (listeners != null && listeners.size() > 0) {
CopyOnWriteArray.Access<OnGlobalLayoutListener> access = listeners.start();
try {
int count = access.size();
for (int i = 0; i < count; i++) {
//进行回调
access.get(i).onGlobalLayout();
}
} finally {
listeners.end();
}
}
}
}
dispatchOnGlobalLayout这个方法就是告诉我们view完成测量的回调。这个方法是在哪个地方执行的?
class ViewRootImpl{
private void performTraversals() {
//layoutRequested主要就是mLayoutRequested,mLayoutRequested在绘制时设置为true
final boolean didLayout = layoutRequested && (!mStopped || mReportNextDraw);
boolean triggerGlobalLayoutListener = didLayout
|| mAttachInfo.mRecomputeGlobalAttributes;
..... 部分代码
if (triggerGlobalLayoutListener) {
mAttachInfo.mRecomputeGlobalAttributes = false;
mAttachInfo.mTreeObserver.dispatchOnGlobalLayout();
}
..... 部分代码
}
}
上面简单分析了ViewTreeObserver的调用过程。
具体的滑动逻辑
public class SlideHelper implements View.OnTouchListener,
ValueAnimator.AnimatorUpdateListener{
@Override
public boolean onTouch(View v, MotionEvent event) {
float touchedArea = event.getRawY() - view.getTop();
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
this.viewHeight = view.getHeight();
startRawY = event.getRawY();
viewStartTranslationY = view.getTranslationY();
//点击区域超过设置卡片滑动区域大小
if (maxTouchable < touchedArea) {
isSlide = false;
}
break;
case MotionEvent.ACTION_MOVE:
float difference = event.getRawY() - startRawY;
float moveTo = viewStartTranslationY + difference;
//isSlide 为false点击区域超过预定区域不移动布局
if (moveTo > 0 && isSlide) {
view.setTranslationY(moveTo);
}
if (event.getRawY() > lastPosition) {
lastPosition = event.getRawY();
}
break;
case MotionEvent.ACTION_UP:
//做了俩个判断进行了布局回收与展开
//如果最大移动像素小于了放开像素和布局移动大于布局的5分之一
//进行回收,否则展开。
boolean slideUp = lastPosition > event.getRawY();
boolean scrollableArea =view.getTranslationY() > view.getHeight() / 5;
if (scrollableArea && !slideUp) {
slideAnimationTo = view.getHeight();
} else {
slideAnimationTo = 0;
}
view.setTranslationY(slideAnimationTo );
lastPosition=0;
isSlide=true;
break;
}
return true;
}
}
上面那个做完全没问题,只是回收或者展开的时候没有美感,我们加个动画让卡片移动顺滑.
public class SlideHelper implements View.OnTouchListener,
ValueAnimator.AnimatorUpdateListener{
@Override
public boolean onTouch(View v, MotionEvent event) {
float touchedArea = event.getRawY() - view.getTop();
if (isAnimationRunning()) {
return false;
}
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
this.viewHeight = view.getHeight();
startRawY = event.getRawY();
viewStartTranslationY = view.getTranslationY();
if (maxTouchable < touchedArea) {
isSlide = false;
}
break;
case MotionEvent.ACTION_MOVE:
float difference = event.getRawY() - startRawY;
float moveTo = viewStartTranslationY + difference;
if (moveTo > 0 && isSlide) {
view.setTranslationY(moveTo);
}
if (event.getRawY() > lastPosition) {
lastPosition = event.getRawY();
}
break;
case MotionEvent.ACTION_UP:
float slideAnimationFrom = view.getTranslationY();
boolean slideUp = lastPosition > event.getRawY();
boolean scrollableArea =view.getTranslationY() > view.getHeight() / 5;
if (scrollableArea && !slideUp) {
slideAnimationTo = view.getHeight();
} else {
slideAnimationTo = 0;
}
valueAnimator.setFloatValues(slideAnimationFrom, slideAnimationTo);
valueAnimator.start();
lastPosition=0;
isSlide=true;
break;
}
return true;
}
//初始化动漫
private void createAnimation() {
valueAnimator = ValueAnimator.ofFloat();
valueAnimator.setDuration(300);
valueAnimator.setInterpolator(new DecelerateInterpolator());
valueAnimator.addUpdateListener(this);
}
//判断动漫是否执行完毕
public boolean isAnimationRunning() {
return valueAnimator != null && valueAnimator.isRunning();
}
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float val = (float) animation.getAnimatedValue();
view.setTranslationY(val);
}
}
动画大家应该比我都熟悉了,我只介绍俩个小知识点
Interpolator
Interpolator 被用来修饰动画效果,定义动画的变化率,可以使存在的动画效果accelerated(加速),decelerated(减速),repeated(重复),bounced(弹跳)等,介绍完了(深入的话自行google)本项目用到decelerated可以看到又快到慢的滑动的。AnimatorUpdateListener
valueAnimator.setFloatValues(slideAnimationFrom, slideAnimationTo);
valueAnimator.start();
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float val = (float) animation.getAnimatedValue();
view.setTranslationY(val);
}
简单说:ValueAnimator 只负责对指定的数字区间进行动画运算
我们需要对运算过程进行监听,然后自己对控件做动画操作