1、java代码
package com.example.administrator.swipelayouttest;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.LinearLayout;
import android.widget.Scroller;
public class SwipeLeftDeleteLayout extends LinearLayout {
/**
* 左滑最大距离
*/
private int swipeLimit;
/**
* 上次点击x坐标
*/
private int lastX = 0;
private Scroller scroller;
public SwipeLeftDeleteLayout(Context context) {
this(context,null);
}
public SwipeLeftDeleteLayout(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public SwipeLeftDeleteLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context);
}
private void initView(Context context) {
setOrientation(HORIZONTAL);
scroller = new Scroller(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int childCount = getChildCount();
if (childCount > 1) {
swipeLimit = getChildAt(1).getMeasuredWidth();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = (int) event.getX();
break;
case MotionEvent.ACTION_MOVE:
int curX = (int) event.getX();
int dx = curX - lastX;
scrollBy(-dx,0);
lastX = curX;
break;
case MotionEvent.ACTION_UP:
if (getScrollX() >= swipeLimit/2) {
// setScrollX(swipeLimit);
smoothScrollTo(swipeLimit, getScrollY());
} else {
// setScrollX(0);
smoothScrollTo(0, getScrollY());
}
invalidate();
break;
}
return true;
}
@Override
public void computeScroll() {
if (scroller.computeScrollOffset()) {
scrollTo(scroller.getCurrX(), scroller.getCurrY());
invalidate();
}
}
/**
* 平滑移动
* @param x
* @param y
*/
private void smoothScrollTo(int x, int y) {
int startX = getScrollX();
int startY = getScrollY();
scroller.startScroll(startX, startY,x - getScrollX(), y - startY);
invalidate();
}
/**
* 边界控制
* @param x
* @param y
*/
@Override
public void scrollTo(int x, int y) {
if (x < 0) {
x = 0;
}
if (x > swipeLimit) {
x = swipeLimit;
}
super.scrollTo(x, y);
}
}
2、xml代码
<?xml version="1.0" encoding="utf-8"?>
<com.example.administrator.swipelayouttest.SwipeLeftDeleteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:text="@string/app_name"
android:textSize="30dp" />
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:textSize="30dp"
android:background="@color/colorAccent"
android:text="delete"/>
</com.example.administrator.swipelayouttest.SwipeLeftDeleteLayout>
第三方左滑控件:SwipeDelMenuLayout
地址:https://github.com/mcxtzhang/SwipeDelMenuLayout