效果如动图所示,Android中要对布局中的控件进行自由拖动,一般有两种实现方法:
方法1:重写父类点击事件的方法, 对触摸事件进行处理。
方法2: 利用ViewDragHelper接管触摸操作来处理触摸事件。
gif图所用的便是方法2。ViewDragHelper提供的callback(ViewDragHelper.Callback)针对 ViewGroup 中的拖拽和重新定位 views 操作时提供了一系列非常有用的方法。下面贴出Demo的核心代码:
布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativelayout_root"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.change.demox.views.bottomsheet.widget.DragLayout
android:id="@+id/drawLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:id="@+id/dragView"
android:layout_width="match_parent"
android:layout_height="32dp"
android:background="@drawable/bg_top_radius_white"
android:elevation="1dp">
<View
android:layout_width="44dp"
android:layout_height="5dp"
android:layout_centerInParent="true"
android:background="@drawable/bg_grey_radius" />
</RelativeLayout>
<FrameLayout
android:id="@+id/frame_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/dragView"
android:background="@color/white"
android:elevation="10dp"
android:padding="1dp">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_machine_part"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</com.change.demox.views.bottomsheet.widget.DragLayout>
</RelativeLayout>
自定义组件:
需要注意的说明,都写在注释里了
package com.change.demox.views.bottomsheet.widget import android.annotation.SuppressLint import android.content.Context import android.os.Bundle import android.os.Parce