1. 程式人生 > >一個簡單的左滑刪除控制元件

一個簡單的左滑刪除控制元件

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;

public class SwipeLeftDeleteLayout extends LinearLayout {

    /**
     * 左滑最大距離
     */
    private int swipeLimit;

    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();
    }

    private void initView() {
        setOrientation(HORIZONTAL);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int childCount = getChildCount();
        if (childCount > 1) {
            swipeLimit = getChildAt(1).getMeasuredWidth();
        }
    }

    int startX = 0;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                startX = (int) event.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                int curX = (int) event.getX();
                int dx = curX - startX;
                scrollBy(-dx,0);
                startX = curX;
                break;
            case MotionEvent.ACTION_UP:
                if (getScrollX() >= swipeLimit/2) {
                    setScrollX(swipeLimit);
                } else {
                    setScrollX(0);
                }
                break;
        }
        return true;
    }

    /**
     * 邊界控制
     * @param x
     * @param y
     */
    @Override
    public void scrollTo(int x, int y) {
        if (x < 0) {
            x = 0;
        }
        if (x > swipeLimit) {
            x = swipeLimit;
        }
        if (x != getScrollX()) {
            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>