1、需求分析及思路分析
今天新鲜出炉的需求来了:产品要在首页上放置一个悬浮图标,这个图标既起着宣传的作用(图标上面有活动标题),也是一个按钮,点击之后能跳转到某个详情页面。而且为了用户体验更好,在滑动界面时,这个图标要乖乖地藏起来,不能影响用户操作。我仔细分析了一下,哟,这不就是中午点外卖时用的饿了么上面的购物车按钮么?
用户没有触摸界面时,购物车就正常悬浮在右下角,当界面滑动时,它就自觉地将自身的一半缩到屏幕之外,而且会变得半透明,不再遮挡底下的内容。到了这一步,相信大家都会想到是用触摸事件来实现了。
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return super.dispatchTouchEvent(event);
}
触摸事件有三种,每一步的作用和实现的效果都不一样:
- 手指按下(ACTION_DOWN):用户手指在屏幕上按下时,记下此时的y坐标作为起始y坐标(startY);
- 手指抬起(ACTION_UP):获取此时的坐标作为结束坐标与
- 手指滑动(ACTION_MOVE):根据手指滑动的距离
2、项目创建及布局编写
创建一个新项目,MainActivity的布局如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.lindroid.floatshoppingcart.MainActivity">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
<ImageView
android:id="@+id/iv_cart"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_

本文详细介绍了如何在Android中实现类似饿了么的悬浮购物车按钮动画效果,包括需求分析、布局编写、触摸事件监听以及动画优化。在用户滑动屏幕时,购物车按钮会自动缩放到屏幕外并变得半透明,手指抬起后会回归原位。通过位移动画和渐变动画结合,以及优化触摸事件处理,提供了流畅的用户体验。
最低0.47元/天 解锁文章
4833





