首页 > 其他分享 >在ListView上滑动显示Delete按钮

在ListView上滑动显示Delete按钮

时间:2023-04-06 21:31:53浏览次数:48  
标签:int hodler private item 按钮 import ListView public Delete


SwipeLayout



实现listview滑动删除功能


http://www.devstore.cn/code/info/579.html



在ListView上滑动显示Delete按钮_ci



首先设置listView.setOnTouchListener(onTouchListener);

listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(onItemClickListener);
listView.setOnTouchListener(onTouchListener);




然后实现onTouchListener


View.OnTouchListener onTouchListener = new View.OnTouchListener() {
		float x, y, ux, uy;
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				x = event.getX();
				y = event.getY();
				break;
			case MotionEvent.ACTION_UP:
				ux = event.getX();
				uy = event.getY();
				index = ((ListView)v).pointToPosition((int) x, (int) y);//item的position
				int p2 = ((ListView)v).pointToPosition((int) ux, (int) uy);
				if (index == p2 && Math.abs(x - ux) > 20) {
					notifyDataSetChanged();
				}
				return false;
			}

			return false;
		}

	};




最后在Adapter中如下实现:


class ListViewAdapter extends BaseAdapter {



		public ListViewAdapter() {
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return orders.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return orders.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHodler hodler;
			if (convertView == null) {
				hodler = new ViewHodler();
				convertView = LayoutInflater.from(context).inflate(R.layout.simple_item_4_for_my_order, null);
				hodler.item_0 = (TextView) convertView.findViewById(R.id.item_0);
				hodler.item_1 = (TextView) convertView.findViewById(R.id.item_1);
				hodler.item_2 = (TextView) convertView.findViewById(R.id.item_2);
				hodler.item_3 = (Button) convertView.findViewById(R.id.item_3);
				hodler.item_4 = (TextView) convertView.findViewById(R.id.item_4);
				convertView.setTag(hodler);
			} else {
				hodler = (ViewHodler) convertView.getTag();
			}
			final Order instance = orders.get(position);

			hodler.item_0.setText(instance.getStoreName());
			hodler.item_1.setText("$"+instance.getPaidAmt()+" for "+instance.getMenuNum()+" items");
			hodler.item_2.setText(instance.getCreateTime());

			if(position==index){
				if(hodler.item_3.getVisibility()==View.VISIBLE){
					hodler.item_3.setVisibility(View.GONE);
					doAnimation(context, hodler.item_3, R.anim.push_right_out);
				}else{
					hodler.item_3.setVisibility(View.VISIBLE);
					doAnimation(context, hodler.item_3, R.anim.push_right_in);
				}
				
					hodler.item_3.setText("Delete");
					hodler.item_3.setOnClickListener(new View.OnClickListener(){
						@Override
						public void onClick(View v) {
							App.order=instance;
							startCommand(context, handler, App.COMMAND_DELETE_ORDER);
						}
					});
				
			}else{
				hodler.item_3.setVisibility(View.GONE);
			}

			
			return convertView;
		}

		class ViewHodler {
			TextView item_0;
			TextView item_1;
			TextView item_2;
			Button item_3;
			TextView item_4;
		}

	}




Adapter布局:


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10dp" 
    android:descendantFocusability="blocksDescendants"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
		<LinearLayout
	            android:layout_width="match_parent"
	            android:layout_height="wrap_content"
	            android:orientation="horizontal" >
	        <TextView
	            android:id="@+id/item_0"
	            android:layout_width="match_parent"
	            android:layout_height="wrap_content"
	            android:textColor="@color/white"
	            android:textSize="@dimen/font_middle"
	            android:textStyle="bold" 
	            android:layout_weight="1"
	            android:singleLine="true"
	            />
	        <TextView
                android:id="@+id/item_4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/white"
                android:textSize="@dimen/font_xsmall" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <TextView
                android:id="@+id/item_1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textColor="@color/white"
                android:textSize="@dimen/font_xsmall" />

            <TextView
                android:id="@+id/item_2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/white"
                android:textSize="@dimen/font_xsmall" />
        </LinearLayout>
    </LinearLayout>

    <Button
        android:id="@+id/item_3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|right"
        android:text="Delete"
        android:textColor="@color/white"
        android:textSize="@dimen/font_middle"
        android:visibility="gone" 
        android:background="@drawable/bg_btn_red"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        />
</FrameLayout>




2个动画文件R.anim.push_right_out,R.anim.push_right_in:


<set xmlns:android="http://schemas.android.com/apk/res/android">
	<translate android:fromXDelta="0" android:toXDelta="100%p" android:duration="300"/>
	<!-- 
	<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />
	 -->
</set>

<set xmlns:android="http://schemas.android.com/apk/res/android">
	<translate android:fromXDelta="100%p" android:toXDelta="0" android:duration="300"/>
	<!-- 
	<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />
	 -->
</set>




另一种手势滑动直接删除的例子:


http://download.csdn.net/detail/xiaanming/6790849

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Scroller;

public class SlideCutListView extends ListView {
	/**
	 * 当前滑动的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;
	/**
	 *  移除item后的回调接口
	 */
	private OnItemRemovedListener onItemRemovedListener;
	/**
	 * 用来指示item滑出屏幕的方向,向左或者向右,用一个枚举值来标记
	 */
	private SlideDirection removeDirection;

	// 滑动删除方向的枚举值
	public enum SlideDirection {
		RIGHT, LEFT;
	}


	public SlideCutListView(Context context) {
		this(context, null);
	}

	public SlideCutListView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public SlideCutListView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
//		screenWidth = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth();
		scroller = new Scroller(context);
		mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
	}
	
	/**
	 * 分发事件,主要做的是判断点击的是那个item, 以及通过postDelayed来设置响应左右滑动事件
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN: {
			// 假如scroller滚动还没有结束,我们直接返回
			if (!scroller.isFinished()) {
				return super.dispatchTouchEvent(event);
			}
			addVelocityTracker(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());
			break;
		}
		case MotionEvent.ACTION_MOVE: {
			if (Math.abs(getXVelocity()) > SNAP_VELOCITY
					|| (Math.abs(event.getX() - downX) > mTouchSlop && Math
							.abs(event.getY() - downY) < mTouchSlop)) {
				isSlide = true;
			}
			break;
		}
		case MotionEvent.ACTION_UP:
			recycleVelocityTracker();
			break;
		}

		return super.dispatchTouchEvent(event);
	}

	/**
	 * 往右滑动,getScrollX()返回的是左边缘的距离,就是以View左边缘为原点到开始滑动的距离,所以向右边滑动为负值
	 */
	private void scrollRight() {
		removeDirection = SlideDirection.RIGHT;
		final int delta = (getWidth() + itemView.getScrollX());
		// 调用startScroll方法来设置一些滚动的参数,我们在computeScroll()方法中调用scrollTo来滚动item
		scroller.startScroll(itemView.getScrollX(), 0, -delta, 0,
				Math.abs(delta));
		postInvalidate(); // 刷新itemView
	}

	/**
	 * 向左滑动,根据上面我们知道向左滑动为正值
	 */
	private void scrollLeft() {
		removeDirection = SlideDirection.LEFT;
		final int delta = (getWidth() - itemView.getScrollX());
		// 调用startScroll方法来设置一些滚动的参数,我们在computeScroll()方法中调用scrollTo来滚动item
		scroller.startScroll(itemView.getScrollX(), 0, delta, 0,
				Math.abs(delta));
		postInvalidate(); // 刷新itemView
	}

	/**
	 * 根据手指滚动itemView的距离来判断是滚动到开始位置还是向左或者向右滚动
	 */
	private void scrollByDistanceX() {
		// 如果向左滚动的距离大于屏幕的三分之一,就让其删除
		if (itemView.getScrollX() >= getWidth() / 3) {
			scrollLeft();
		} else if (itemView.getScrollX() <= -getWidth() / 3) {
			scrollRight();
		} else {
			// 滚回到原始位置,为了偷下懒这里是直接调用scrollTo滚动
			itemView.scrollTo(0, 0);
		}

	}

	/**
	 * 处理我们拖动ListView item的逻辑
	 */
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		if (isSlide && slidePosition != AdapterView.INVALID_POSITION) {
			addVelocityTracker(ev);
			final int action = ev.getAction();
			int x = (int) ev.getX();
			switch (action) {
			case MotionEvent.ACTION_MOVE:
				int deltaX = downX - x;
				downX = x;

				// 手指拖动itemView滚动, deltaX大于0向左滚动,小于0向右滚
				itemView.scrollBy(deltaX, 0);
				break;
			case MotionEvent.ACTION_UP:
				int velocityX = getXVelocity();
				if (velocityX > SNAP_VELOCITY) {
					scrollRight();
				} else if (velocityX < -SNAP_VELOCITY) {
					scrollLeft();
				} else {
					scrollByDistanceX();
				}

				recycleVelocityTracker();
				// 手指离开的时候就不响应左右滚动
				isSlide = false;
				break;
			}

			return true; // 拖动的时候ListView不滚动
		}

		//否则直接交给ListView来处理onTouchEvent事件
		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 (onItemRemovedListener == null) {
					throw new NullPointerException("OnItemRemovedListener is null, we should called setOnItemRemovedListener()");
				}
				
				itemView.scrollTo(0, 0);
				onItemRemovedListener.onItemRemoved(removeDirection, slidePosition);
			}
		}
	}

	/**
	 * 添加用户的速度跟踪器
	 * 
	 * @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 getXVelocity() {
		velocityTracker.computeCurrentVelocity(1000);
		int velocity = (int) velocityTracker.getXVelocity();
		return velocity;
	}

	/**
	 * 设置滑动删除的回调接口
	 * @param removeListener
	 */
	public void setOnItemRemovedListener(OnItemRemovedListener onItemRemovedListener) {
		this.onItemRemovedListener = onItemRemovedListener;
	}
	
	/**
	 * 
	 * 当ListView item滑出屏幕,回调这个接口
	 * 我们需要在回调方法removeItem()中移除该Item,然后刷新ListView
	 * 
	 *
	 */
	public interface OnItemRemovedListener {
		public void onItemRemoved(SlideDirection direction, int position);
	}

}



用法:


import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.example.slidecutlistview.SlideCutListView.OnItemRemovedListener;
import com.example.slidecutlistview.SlideCutListView.SlideDirection;

public class MainActivity extends Activity implements OnItemRemovedListener{
	private SlideCutListView slideCutListView ;
	private ArrayAdapter<String> adapter;
	private List<String> datas = new ArrayList<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		init();
	}

	private void init() {
		slideCutListView = (SlideCutListView) findViewById(R.id.slideCutListView);
		slideCutListView.setOnItemRemovedListener(this);
		
		for(int i=0; i<40; i++){
			datas.add("item" + i); 
		}
		
		adapter = new ArrayAdapter<String>(this, R.layout.listview_item, R.id.list_item, datas);
		slideCutListView.setAdapter(adapter);
		
		slideCutListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Toast.makeText(MainActivity.this, datas.get(position), Toast.LENGTH_SHORT).show();
			}
		});
	}

	@Override
	public void onItemRemoved(SlideDirection direction, int position) {
		adapter.remove(adapter.getItem(position));
		switch (direction) {
		case RIGHT:
			Toast.makeText(this, "position="+ position, Toast.LENGTH_SHORT).show();
			break;
		case LEFT:
			Toast.makeText(this, "position="+ position, Toast.LENGTH_SHORT).show();
			break;

		default:
			break;
		}
		
	}	
}




仿微信的删除,效果还可以,就是封装的不够,代码之间瓜葛太大:





实现listview中item滑动效果:Swipemenulistview


http://www.open-open.com/lib/view/open1430107254865.html


标签:int,hodler,private,item,按钮,import,ListView,public,Delete
From: https://blog.51cto.com/u_5454003/6174181

相关文章

  • ListView之setEmptyView的问题
    使用listView或者gridView时,当列表为空时,有时需要显示一个特殊的emptyview来提示用户,一般情况下,如果你是继承ListActivity,只要<ListViewandroid:id="@id/android:list".../><TextViewandroid:id="@id/android:empty.../>当列表为空时就会自动显示Tex......
  • WinCE5.0下实现透明背景按钮(.net C#) 个人实验
    参考了WinCE5.0下实现透明背景按钮(.netC#)这篇文章后,本着不模仿的态度去做,结果发现还是原先作者的思路比较好,自己的做法虽然比较简单当时图片得做很多张,效果其实也差不多,而且可维护性并不强,先把我自己做的贴出来。希望自己多敲敲,能找出更简单的方案来目录试图:效果: 直接贴代码:us......
  • 网页一键分享按钮HTML代码
    在网页中加入以下代码可以实现网页的一键分享:<!DOCTYPEhtml><html><head><METAhttp-equiv="content-type"content="text/html;charset="UTF-8"><title>Inserttitlehere</title></head><body><divclass......
  • uni-app:tabbar自定义中间凸起按钮的tabbar(hbuilderx 3.7.3)
    一,官方文档地址:https://uniapp.dcloud.net.cn/collocation/pages.html#tabbarhttps://uniapp.dcloud.net.cn/api/ui/tabbar.html#ontabbarmidbuttontap二,代码1,pages.json"tabBar":{"color":"#7A7E83",//字体颜色"sel......
  • shared_ptr 自定义 deleter 删除器
    make_shared不支持自定义删除器shared_ptr<Bar>sp2(sp1,deleter1);无法指定自定义删除器?《C++Primer5th》P413错误?sp1不能是智能指针,可以是内置指针reset参数为内置指针,可以重新指定删除器测试代码classBar{public:Bar(intii):i(ii){cout<<......
  • JS实现自动倒计时30秒后按钮才可用
    WEB开发中经常会用到倒计时来限制用户对表单的操作,比如希望用户在一定时间内看完相关协议信息才允许用户继续下一步操作,又比如在收取手机验证码时允许用户在一定时间过后(未收到验证码的情况下)再次获取验证码。那么今天我来给大家介绍下如何使用Javascript来实现这一简单应用。应......
  • cxgrid行内编辑按钮
    cxgrid行内编辑按钮在每行的数据最后一列显示一个按钮,点击按钮删除对应的数据。使用cxGrid能完美实现。1、设置按钮列的properties是buttonedit2、设置properties下的属性 viewStyle=vsButtonsAutoWidth3、设置Options中的 ShowEditButtons=isebAlways4、点击properties下......
  • 用户路由及按钮权限管理
    需求背景:当我们在做后台管理系统的时候,都会涉及到系统的菜单树如何动态显示的问题。目前基本上都是RBAC的解决方案,即Role-Based Access Control,权限与角色相关联,给用户通设置适当角色的而得到角色的权限 路由权限方案:1、前端路由根据角色控制页面权限:即为每个页面设置允许......
  • 为什么 B 页面的 unload 事件在刷新后点击浏览器的返回按钮不触发?
    ......
  • android点击按钮弹出复选框
    String[]items={"餐饮","出行","娱乐","学习","日用品","其他"};Stringconsumetype="";List<String>mytypes=newArrayList<>();AlertDialog.Builderbuilder=newAlertDialog.Builder(addmes......