Android:跟手滑动的布局ViewGroup

本文介绍了如何在Android中实现跟手滑动的布局,通过监听触摸事件并动态调整ViewGroup的位置,结合ValueAnimator实现平滑的动画效果。示例中详细讲解了XML布局、MainActivity中的关键方法,如slideToShow和slideToHide,以及如何处理onTouch事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

跟手滑动

很多开发者对布局的跟手滑动不太了解,在此就举一个例子,看一个RelativeLayout的滑动显示

原理

无论是跟手滑动,还是弹入弹出动画,本质上都是修改View或ViewGroup的位置,也即是setX() setY()这两个方法。

  • 跟手滑动

跟手滑动是指,当用户在屏幕上滑动时,某一块布局,随着手指的滑动而滑动。所以,它的实现原理就是在onTouch事件中动态获得手指滑动的距离,然后修改view的位置。

  • 弹入弹出动画

跟手滑动时,有可能用户只滑出来View的一部分就松手了,为了效果更好,我们按照用户的滑动方向,将view以动画的形式显示出来。所以,它的原理就是使用ValueAnimator,动态修改view的位置

Code

xml布局

我们的目的是让id为rl_left的RelativeLayout,从屏幕左边随手滑出,也可以隐藏到屏幕左侧。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white" >

    <Button
        android:id="@+id/btn_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:text="show" />

    <Button
        android:id="@+id/btn_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_below="@id/btn_1"
        android:text="hide" />

    <TextView
        android:id="@+id/tv_show"
        android:layout_width="wrap_content"
        
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值