今天上午我出了一篇 Android 史上最简单的自定义listview上拉刷新下拉加载,有位网友询问我说如果在这个基础上在实现滑动编辑和删除可以么。我回答说,这个是可以的。下面我们一起来看一下具体怎么实现的吧
如果不需要侧滑删除和修改的童鞋可以看我的这篇文章 Android 史上最简单的自定义listview上拉刷新下拉加载
文章地址:https://blog.csdn.net/k571039838k/article/details/82049771
废话不多说,老规矩,上运行截图
初始页面
下拉刷新
上拉加载
侧滑页面
点击编辑
点击删除
先看一下我们的项目结构
咦,看过我的上一篇文章的小伙伴们可能会说,怎么这么简单?就多了一个adapter文件、一个listItem和一个item布局文件?是的没错,就是这么简单,这么强大。
不吹牛了,开始看实现过程
首先看我们的Myadapter文件
package com.example.utils;
import java.util.List;
import com.example.listdemo.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
public class Myadapter extends BaseAdapter {
private List mData;
private LayoutInflater mInflater;
private ViewHolder mHolder;
private OnSlideClickListener mListener;
@Override
public int getCount() {
return mData == null ? 0 : mData.size();
}
class ViewHolder{
TextView tv;
View front;
Button btnClock;
Button btnDelete;
}
public interface OnSlideClickListener{
public void onItemClick(int position, View item);
public void onClockClick(int position, View item);
public void onDeleteClick(int position, View item);
}
public Myadapter(Context context, List data, OnSlideClickListener listener){
this.mData = data;
this.mInflater = LayoutInflater.from(context);
this.mListener = listener;
}
@Override
public Object getItem(int position) {
return mData == null ? null : mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = mInflater.inflate(R.layout.item_listview, null);
mHolder = new ViewHolder();
mHolder.tv = (TextView) convertView.findViewById(R.id.tv);
mHolder.front = convertView.findViewById(R.id.front);
mHolder.btnClock = (Button) convertView.findViewById(R.id.btnClock);
mHolder.btnDelete = (Button) convertView.findViewById(R.id.btnDelete);
convertView.setTag(mHolder);
}else{
mHolder = (ViewHolder) convertView.getTag();
}
mHolder.tv.setText(getItem(position)+"");
// 使隐藏的按钮数量不一样,测试可滑动范围
mHolder.btnClock.setVisibility(position%2==0 ? View.GONE : View.VISIBLE);
if(mListener != null){
final int pos = position;
final View item = convertView;
mHolder.btnClock.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mListener.onClockClick(pos, item);
}
});
mHolder.btnDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mListener.onDeleteClick(pos, item);
}
});
mHolder.front.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mListener.onItemClick(pos, item);
}
});
}
return convertView;
}
}
这个适配器就是最基础的适配器实现过程啦,这里就不过多解释了
下面是我们的SlideListItem文件,主要用来展示侧滑修改与删除按钮的点击事件捕捉
package com.example.utils;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
public class SlideListItem extends LinearLayout {
public SlideListItem(Context context) {
this(context, null);
}
public SlideListItem(Context context, AttributeSet attrs) {
super(context, attrs);
}
@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);
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
Log.d("test", "event : " + event);
return super.dispatchTouchEvent(event);
}
@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;
}
}
}
}
接着使我们的最核心文件,自定义ListView文件,注释很清楚,大家要认真看
package com.example.utils;
import java.text.SimpleDateFormat;
import com.example.listdemo.R;
import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Scroller;
import android.widget.TextView;
import android.view.WindowManager;
/**
*
* @author 自定义listview实现上拉刷新和下拉加载 2018-08-25 刘明昆 q571039838
*
*/
public class MyListViewUtils extends ListView implements
AbsListView.OnScrollListener {
private View bottomview; // 尾文件
private View headview; // 头文件
private int totaItemCounts;// 用于表示是下拉还是上拉
private int lassVisible; // 上拉
private int firstVisible; // 下拉
private LoadListener loadListener; // 接口回调
private int bottomHeight;// 尾文件高度
private int headHeight; // 头文件高度
private int Yload;// 位置
boolean isLoading;// 加载状态
private TextView headtxt;// 头文件textview显示加载文字
private TextView headtime;// 头文件textview显示加载时间
private ProgressBar progressBar;// 加载进度
/**
* 当前滑动的ListView position
*/
private int slidePosition;
/**
* 手指按下X的坐标
*/
private int downY;
/**
* 手指按下Y的坐标
*/
private int downX;
/**
* 屏幕宽度
*/
private int screenWidth;
/**
* ListView的item
*/
private View itemView;
/**
* 滑动类
*/
private Scroller scroller;
/**
* 滑动速度边界值
*/
private static final int SNAP_VELOCITY = 600;
/**
* 速度追踪对象
*/
private VelocityTracker velocityTracker;
/**
* 是否响应滑动,默认为不响应
*/
private boolean isSlide = false;
/**
* 认为是用户滑动的最小距离
*/
private int mTouchSlop;
/**
* 最多可滑动的范围
*/
private int mTouchLimit;
/**
* 移除item后的回调接口
*/
private RemoveListener mRemoveListener;
/**
* 是否已经侧滑
*/
private boolean hasSlided = false;
public MyListViewUtils(Context context) {
super(context);
Init(context);
}
public MyListViewUtils(Context context, AttributeSet attrs) {
super(context, attrs);
Init(context);
}
public MyListViewUtils(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
Init(context);
}
/**
* 设置滑动删除的回调接口
*
* @param removeListener
*/
public void setRemoveListener(RemoveListener removeListener) {
this.mRemoveListener = removeListener;
}
/**
* 设置可滑动的最大值
*
* @param limit
*/
public void setTouchLimit(int limit) {
this.mTouchLimit = limit;
}
/**
* 获取可滑动的最大值
*
* @return
*/
public int getTouchLimit() {
return this.mTouchLimit;
}
/**
* 退回原位
*/
public void slideBack() {
if (hasSlided && itemView != null) {
scrollXBy(itemView, -mTouchLimit);
hasSlided = false;
}
}
/**
* 分发事件,主要做的是判断点击的是那个item, 以及通过postDelayed来设置响应左右滑动事件
*/
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
addVelocityTracker(event);
// 假如scroller滚动还没有结束,我们直接返回
if (!scroller.isFinished()) {
return super.dispatchTouchEvent(event);
}
// 如果已经侧滑了,我们直接返回
if (hasSlided) {
return super.dispatchTouchEvent(event);
}
downX = (int) event.getX();
downY = (int) event.getY();
slidePosition = pointToPosition(downX, downY);
// 无效的position, 不做任何处理
if (slidePosition == AdapterView.INVALID_POSITION) {
return super.dispatchTouchEvent(event);
}
// 获取我们点击的item view
itemView = getChildAt(slidePosition - getFirstVisiblePosition());
if (itemView instanceof SlideListItem) {
SlideListItem item = (SlideListItem) itemView;
int count = item.getChildCount();
mTouchLimit = 0;
for (int i = 0; i < count; i++) {
if (i > 0) {
mTouchLimit += item.getChildAt(i).getMeasuredWidth();
}
}
}
break;
}
case MotionEvent.ACTION_MOVE: {
if (Math.abs(getScrollVelocity()) > SNAP_VELOCITY
|| (downX - event.getX() > mTouchSlop && Math.abs(event
.getY() - downY) < mTouchSlop)) {
isSlide = true;
}
break;
}
case MotionEvent.ACTION_UP:
recycleVelocityTracker();
break;
}
return super.dispatchTouchEvent(event);
}
private void Init(Context context) {
// 拿到头布局文件xml
headview = LinearLayout.inflate(context, R.layout.head, null);
headtxt = (TextView) headview.findViewById(R.id.headtxt);
headtime = (TextView) headview.findViewById(R.id.timetxt);
progressBar = (ProgressBar) headview.findViewById(R.id.headprogress);
headtime.setText("上次更新时间:"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System
.currentTimeMillis()));
// 拿到尾布局文件
bottomview = LinearLayout.inflate(context, R.layout.bottom, null);
// 测量尾文件高度
bottomview.measure(0, 0);
// 拿到高度
bottomHeight = bottomview.getMeasuredHeight();
// 隐藏view
bottomview.setPadding(0, -bottomHeight, 0, 0);
headview.measure(0, 0);
headHeight = headview.getMeasuredHeight();
headview.setPadding(0, -headHeight, 0, 0);
// 添加listview底部
this.addFooterView(bottomview);
// 添加到listview头部
this.addHeaderView(headview);
// 设置拉动监听
this.setOnScrollListener(this);
DisplayMetrics dm = new DisplayMetrics();
((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay().getMetrics(dm);
screenWidth = dm.widthPixels;
scroller = new Scroller(context);
mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
mTouchLimit = screenWidth / 4;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
// 如果已经侧滑了,回归原位
if (hasSlided) {
scrollXBy(itemView, -mTouchLimit);
hasSlided = false;
// 拦截事件,不继续处理
return false;
}
if (isSlide && slidePosition != AdapterView.INVALID_POSITION) {
requestDisallowInterceptTouchEvent(true);
addVelocityTracker(ev);
final int action = ev.getAction();
int x = (int) ev.getX();
switch (action) {
case MotionEvent.ACTION_DOWN:
Yload = (int) ev.getY();
break;
case MotionEvent.ACTION_MOVE:
int moveY = (int) ev.getY();
int paddingY = headHeight + (moveY - Yload) / 2;
if (paddingY < 0) {
headtxt.setText("下拉刷新........");
progressBar.setVisibility(View.GONE);
}
if (paddingY > 0) {
headtxt.setText("松开刷新........");
progressBar.setVisibility(View.GONE);
}
headview.setPadding(0, paddingY, 0, 0);
MotionEvent cancelEvent = MotionEvent.obtain(ev);
cancelEvent
.setAction(MotionEvent.ACTION_CANCEL
| (ev.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
onTouchEvent(cancelEvent);
int deltaX = downX - x;
downX = x;
// 手指拖动itemView滚动, deltaX大于0向左滚动,小于0向右滚
scrollXBy(itemView, deltaX);
return true; // 拖动的时候ListView不滚动
case MotionEvent.ACTION_UP:
int velocityX = getScrollVelocity();
if (velocityX < -SNAP_VELOCITY) {
scrollLeft();
} else {
scrollByDistanceX();
}
recycleVelocityTracker();
// 手指离开的时候就不响应左右滚动
isSlide = false;
break;
}
}
return super.onTouchEvent(ev);
}
@Override
public void computeScroll() {
// 调用startScroll的时候scroller.computeScrollOffset()返回true,
if (scroller.computeScrollOffset()) {
// 让ListView item根据当前的滚动偏移量进行滚动
itemView.scrollTo(scroller.getCurrX(), scroller.getCurrY());
postInvalidate();
// 滚动动画结束的时候调用回调接口
if (scroller.isFinished()) {
if (mRemoveListener != null) {
mRemoveListener.removeItem(slidePosition);
}
}
}
}
/**
* 向左滑动,根据上面我们知道向左滑动为正值
*/
private void scrollLeft() {
final int delta = (mTouchLimit - itemView.getScrollX());
// 调用startScroll方法来设置一些滚动的参数,我们在computeScroll()方法中调用scrollTo来滚动item
scroller.startScroll(itemView.getScrollX(), 0, delta, 0,
Math.abs(delta));
postInvalidate(); // 刷新itemView
hasSlided = true;
}
/**
* 根据手指滚动itemView的距离来判断是滚动到开始位置还是向左或者向右滚动
*/
private void scrollByDistanceX() {
// 如果向左滚动的距离大于屏幕的二分之一,就让其删除
if (itemView.getScrollX() >= mTouchLimit / 2) {
scrollLeft();
} else {
// 滚回到原始位置,为了偷下懒这里是直接调用scrollTo滚动
itemView.scrollTo(0, 0);
}
}
/**
* 添加用户的速度跟踪器
*
* @param event
*/
private void addVelocityTracker(MotionEvent event) {
if (velocityTracker == null) {
velocityTracker = VelocityTracker.obtain();
}
velocityTracker.addMovement(event);
}
/**
* 移除用户速度跟踪器
*/
private void recycleVelocityTracker() {
if (velocityTracker != null) {
velocityTracker.recycle();
velocityTracker = null;
}
}
/**
* 获取X方向的滑动速度,大于0向右滑动,反之向左
*
* @return
*/
private int getScrollVelocity() {
velocityTracker.computeCurrentVelocity(1000);
int velocity = (int) velocityTracker.getXVelocity();
return velocity;
}
/**
*
* 当ListView item滑出屏幕,回调这个接口 我们需要在回调方法removeItem()中移除该Item,然后刷新ListView
*
* @author xiaanming
*
*/
public interface RemoveListener {
public void removeItem(int position);
}
/**
* 让指定的view滚动x位置,设置左右边界,view最多滚动到边界位置
*
* @param view
* @param x
*/
private void scrollXBy(View view, int x) {
// 如果已经滑动了最大值,并希望继续向左滑,忽略
if (view.getScrollX() >= mTouchLimit && x >= 0)
return;
// 如果已经回到原位,并希望继续想右划,忽略
if (view.getScrollX() <= 0 && x <= 0)
return;
if (view.getScrollX() + x > mTouchLimit) {
x = mTouchLimit - view.getScrollX();
} else if (view.getScrollX() + x < 0) {
x = -view.getScrollX();
}
view.scrollBy(x, 0);
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (totaItemCounts == lassVisible && scrollState == SCROLL_STATE_IDLE) {
if (!isLoading) {
isLoading = true;
bottomview.setPadding(0, 0, 0, 0);
// 加载数据
loadListener.onLoad();
}
}
if (firstVisible == 0 && scrollState == SCROLL_STATE_IDLE) {
headview.setPadding(0, 0, 0, 0);
headtxt.setText("正在刷新.......");
progressBar.setVisibility(View.VISIBLE);
loadListener.PullLoad();
}
}
// 接口回调
public interface LoadListener {
void onLoad();
void PullLoad();
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
this.firstVisible = firstVisibleItem;
this.lassVisible = firstVisibleItem + visibleItemCount;
this.totaItemCounts = totalItemCount;
}
// 加载完成
public void loadComplete() {
isLoading = false;
bottomview.setPadding(0, -bottomHeight, 0, 0);
headview.setPadding(0, -headHeight, 0, 0);
}
public void setInteface(LoadListener loadListener) {
this.loadListener = loadListener;
}
}
最后就是我们的item布局文件了,做过listView加载数据的童鞋应该就很熟悉这个布局文件,且这个文件没有任何技术含量
到这里代码基本上就玩了,是不是很简单?
(实在是缺分用,如果没分的童鞋也没关系,留邮箱,我发他代码)
最后附上我的这个demo下载地址:https://download.csdn.net/download/k571039838k/10626639
最后感谢大家的支持