ListView侧滑效果

项目做完了闲着没事研究一下自定listview的侧滑效果,现在共享给大家希望对大家有帮助
如果发现bug希望大家尽管回复我会修改的


自定义Listview

package com.example.gzl.mapplication.wedig;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;

/**
 * Created by gzl on 2016/3/3
 */
public class MyListView extends ListView {

    private float minDis = 10;
    private float mLastMotionX;// 记住上次X触摸屏的位置
    private float mLastMotionY;// 记住上次Y触摸屏的位置
    private boolean isLock = false;

    public MyListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (!isIntercept(ev)) {
            return false;
        }
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        boolean dte = super.dispatchTouchEvent(event);
        if (MotionEvent.ACTION_UP == event.getAction() && !dte) {//onItemClick
            int position = pointToPosition((int) event.getX(), (int) event.getY());//被点击的条目在当前页面的位置
            int fetch;//listView被点击的item的position
            if (getLastVisiblePosition() >= getChildCount()) {//判断是不是listView的第一页
                //不是第一页
                fetch = getChildCount() - 1 - (getLastVisiblePosition() - position);
                fetch = fetch + getFirstVisiblePosition();
                Log.e("false","true");
            } else {
                //是第一页
                fetch = position;
            }
            Log.e( "position","getLastVisiblePosition():" + getLastVisiblePosition() + "getChildCount():" + getChildCount() + position + "=========fetch:" + fetch);
            super.performItemClick(getAdapter().getView(fetch, null, null), fetch, getItemIdAtPosition(fetch));
        }
        return dte;
    }

    @Override
    public boolean performClick() {
        return super.performClick();
    }

    @Override
    public boolean performItemClick(View view, int position, long id) {
        return super.performItemClick(view, position, id);
    }

    /**
     * 检测是ListView滑动还是item滑动
     * true listview滑动  false item滑动
     */
    private boolean isIntercept(MotionEvent ev) {
        float x = ev.getX();
        float y = ev.getY();
        int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mLastMotionX = x;
                mLastMotionY = y;
                break;
            case MotionEvent.ACTION_MOVE:
                if (!isLock) {
                    float deltaX = Math.abs(mLastMotionX - x);
                    float deltay = Math.abs(mLastMotionY - y);
                    mLastMotionX = x;
                    mLastMotionY = y;
                    if (deltaX > deltay && deltaX > minDis) {
                        isLock = true;
                        return false;
                    }
                } else {
                    return false;
                }
                break;
            case MotionEvent.ACTION_UP:
                isLock = false;
                break;
            case MotionEvent.ACTION_CANCEL:
                isLock = false;
                break;
        }
        return true;
    }

}

自定义Item

package com.example.gzl.mapplication.wedig;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Scroller;

/**
 * Created by gzl on 2016/3/3.
 *
 */
public class MyListViewItem extends LinearLayout {

    private Scroller mScroller;// 滑动控制
    private float mLastMotionX;// 记住上次触摸屏的位置
    private int deltaX;
    private int back_width;
    private float downX;
    public boolean isdelet = false;

    public MyListViewItem(Context context) {
        super(context);
        init(context);
    }

    public MyListViewItem(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public void setIsdelet(boolean isdelet) {
        this.isdelet = isdelet;
        if(isdelet){
            scrollTo(back_width, 0);
        }else{
            scrollTo(0, 0);
        }
    }

    private void init(Context context) {
        mScroller = new Scroller(context);
    }

    /**
     * computeScroll在父控件执行drawChild时,会调用这个方法
     */
    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            postInvalidate();//刷新界面
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            measureChild(getChildAt(i), widthMeasureSpec, heightMeasureSpec);
            if (i == 1) {
                back_width = getChildAt(i).getMeasuredWidth();
            }
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        float x = event.getX();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mLastMotionX = x;
                downX = x;
                break;
            case MotionEvent.ACTION_MOVE:
                deltaX = (int) (mLastMotionX - x);
                mLastMotionX = x;
                int scrollx = getScrollX() + deltaX;
                if (scrollx > 0 && scrollx < back_width) {
                    scrollBy(deltaX, 0);
                } else if (scrollx > back_width) {
                    scrollTo(back_width, 0);
                } else if (scrollx < 0) {
                    scrollTo(0, 0);
                }
                break;
            case MotionEvent.ACTION_UP:
                int scroll = getScrollX();
                if (scroll > back_width / 2) {
                    scrollTo(back_width, 0);
                    isdelet = true;
                } else {
                    scrollTo(0, 0);
                    isdelet = false;
                }
                if (Math.abs(x - downX) < 5) {
                    return false;
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                scrollTo(0, 0);
                break;
        }
        return true;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int margeLeft = 0;
        int size = getChildCount();
        for (int i = 0; i < size; i++) {
            View view = getChildAt(i);
            if (view.getVisibility() != View.GONE) {
                int childWidth = view.getMeasuredWidth();
                view.layout(margeLeft, 0, margeLeft + childWidth,
                        view.getMeasuredHeight());
                margeLeft += childWidth;
            }
        }
    }
}

MainActivity.java

package com.example.gzl.mapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import com.example.gzl.mapplication.adapter.MyAdapter;
import com.example.gzl.mapplication.wedig.MyListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity implements AdapterView.OnItemClickListener {

    private MyListView my_listview;
    public MyAdapter myAdapter;
    private List<Object> myList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        my_listview = (MyListView) findViewById(R.id.my_listview);
        setData();
        myAdapter = new MyAdapter(MainActivity.this);
        myAdapter.setmDatas(myList);
        my_listview.setAdapter(myAdapter);
        my_listview.setOnItemClickListener(this);
    }

    private void setData() {
        for (int i = 0; i < 20; i++) {
            myList.add("我是item" + i);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(parent.getContext(), "点击了" + position, Toast.LENGTH_SHORT).show();
    }
}

MyAdapter.java

package com.example.gzl.mapplication.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.gzl.mapplication.R;
import com.example.gzl.mapplication.wedig.MyListViewItem;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhaohua on 2016/3/3.
 */
public class MyAdapter extends BaseAdapter {
    private Context mContext;
    private List<Object> mDatas;

    public MyAdapter(Context context) {
        this.mContext = context;
        mDatas = new ArrayList<>();
    }

    public void setmDatas(List<Object> mDatas) {
        this.mDatas = mDatas;
    }

    @Override
    public int getCount() {
        if (mDatas.size() > 0) {
            return mDatas.size();
        } else {
            return 0;
        }
    }

    @Override
    public Object getItem(int position) {
        return mDatas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHoder myViewHoder;
        if (convertView == null) {
            myViewHoder = new ViewHoder();
            convertView = View.inflate(mContext, R.layout.listview_item, null);
            myViewHoder.myitemtext = (TextView) convertView.findViewById(R.id.myitemtext);
            myViewHoder.mybtnBj = (Button) convertView.findViewById(R.id.mybtnBj);
            myViewHoder.mybtnDelete = (Button) convertView.findViewById(R.id.mybtnDelete);
            convertView.setTag(myViewHoder);
        } else {
            myViewHoder = (ViewHoder) convertView.getTag();
        }
        myViewHoder.myitemtext.setText(mDatas.get(position).toString());
        ((MyListViewItem)convertView).setIsdelet(false);
        myViewHoder.mybtnBj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, "点击了标记", Toast.LENGTH_SHORT).show();
            }
        });
        myViewHoder.mybtnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, "点击了删除", Toast.LENGTH_SHORT).show();
            }
        });

        return convertView;

    }

    class ViewHoder {
        TextView myitemtext;
        Button mybtnBj;
        Button mybtnDelete;
    }
}
listviewitem.java

package com.example.gzl.mapplication.wedig;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Scroller;

/**
 * Created by gzl on 2016/3/3.
 *
 */
public class MyListViewItem extends LinearLayout {

    private Scroller mScroller;// 滑动控制
    private float mLastMotionX;// 记住上次触摸屏的位置
    private int deltaX;
    private int back_width;
    private float downX;
    public boolean isdelet = false;

    public MyListViewItem(Context context) {
        super(context);
        init(context);
    }

    public MyListViewItem(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public void setIsdelet(boolean isdelet) {
        this.isdelet = isdelet;
        if(isdelet){
            scrollTo(back_width, 0);
        }else{
            scrollTo(0, 0);
        }
    }

    private void init(Context context) {
        mScroller = new Scroller(context);
    }

    /**
     * computeScroll在父控件执行drawChild时,会调用这个方法
     */
    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            postInvalidate();//刷新界面
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            measureChild(getChildAt(i), widthMeasureSpec, heightMeasureSpec);
            if (i == 1) {
                back_width = getChildAt(i).getMeasuredWidth();
            }
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        float x = event.getX();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mLastMotionX = x;
                downX = x;
                break;
            case MotionEvent.ACTION_MOVE:
                deltaX = (int) (mLastMotionX - x);
                mLastMotionX = x;
                int scrollx = getScrollX() + deltaX;
                if (scrollx > 0 && scrollx < back_width) {
                    scrollBy(deltaX, 0);
                } else if (scrollx > back_width) {
                    scrollTo(back_width, 0);
                } else if (scrollx < 0) {
                    scrollTo(0, 0);
                }
                break;
            case MotionEvent.ACTION_UP:
                int scroll = getScrollX();
                if (scroll > back_width / 2) {
                    scrollTo(back_width, 0);
                    isdelet = true;
                } else {
                    scrollTo(0, 0);
                    isdelet = false;
                }
                if (Math.abs(x - downX) < 5) {
                    return false;
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                scrollTo(0, 0);
                break;
        }
        return true;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int margeLeft = 0;
        int size = getChildCount();
        for (int i = 0; i < size; i++) {
            View view = getChildAt(i);
            if (view.getVisibility() != View.GONE) {
                int childWidth = view.getMeasuredWidth();
                view.layout(margeLeft, 0, margeLeft + childWidth,
                        view.getMeasuredHeight());
                margeLeft += childWidth;
            }
        }
    }
}




Item布局

<?xml version="1.0" encoding="utf-8"?>
<com.example.gzl.mapplication.wedig.MyListViewItem xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/myitemtext"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:text="测试数据" />
    </RelativeLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical">

        <Button
            android:id="@+id/mybtnBj"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="@color/biaoji_bg"
            android:text="标记" />

        <Button
            android:id="@+id/mybtnDelete"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="@color/delet_bg"
            android:text="删除" />
    </LinearLayout>
</com.example.gzl.mapplication.wedig.MyListViewItem>

main_activity布局

<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"
    tools:context=".MainActivity">

    <com.example.gzl.mapplication.wedig.MyListView
        android:id="@+id/my_listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none"/>

</RelativeLayout>


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值