listview滑动删除
时间: 2023-07-28 09:07:56 浏览: 115
Android listview 滑动删除(具体效果360手机卫士后台通知)-IT计算机-毕业设计.zip
要实现ListView滑动删除的功能,可以采用以下步骤:
1. 首先创建一个ListView,并给ListView设置一个适配器;
2. 在适配器的getView()方法中,为每一个item添加一个滑动删除的功能;
3. 在item中添加一个布局,该布局包含两个子控件:一个是要显示的内容,另一个是删除按钮;
4. 给删除按钮添加点击事件,当点击删除按钮时,将该item从ListView中移除;
5. 在ListView的OnTouchListener中,监听手势滑动事件,并实现滑动删除的效果。
下面是一个简单的实现代码:
```
public class MyAdapter extends BaseAdapter implements View.OnTouchListener {
private Context mContext;
private List<String> mData;
private int mLastPosition;
private int mDownX, mDownY;
private boolean isSlide = false;
public MyAdapter(Context context, List<String> data) {
mContext = context;
mData = data;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_layout, null);
viewHolder = new ViewHolder();
viewHolder.contentTv = convertView.findViewById(R.id.content_tv);
viewHolder.deleteBtn = convertView.findViewById(R.id.delete_btn);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.contentTv.setText(mData.get(position));
viewHolder.deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mData.remove(position);
notifyDataSetInvalidated();
}
});
convertView.setOnTouchListener(this);
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 点击事件
}
});
return convertView;
}
static class ViewHolder {
TextView contentTv;
Button deleteBtn;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
mDownX = (int) event.getX();
mDownY = (int) event.getY();
mLastPosition = v.getId();
isSlide = false;
break;
case MotionEvent.ACTION_MOVE:
int moveX = (int) event.getX();
int moveY = (int) event.getY();
int deltaX = moveX - mDownX;
int deltaY = moveY - mDownY;
if (Math.abs(deltaX) > Math.abs(deltaY)) {
isSlide = true;
// 滑动事件
}
break;
case MotionEvent.ACTION_UP:
if (!isSlide) {
// 点击事件
}
break;
}
return true;
}
}
```
阅读全文