andorid 中如何实现双击事件

项目需求:

    android中只有单击和其他事件,其实都是由OnTouch事件演变而来;最近有项目要求双击全屏,所以就试着实现了下


具体实现如下:


1.MainActivity.java实现:

public class MainActivity extends Activity implements OnTouchListener {
	private long firstClick;
	private long lastClick;
	// 计算点击的次数
	private int count;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		findViewById(R.id.ontourch).setOnTouchListener(this);
	}

	@Override
	public boolean onTouch(View arg0, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			// 如果第二次点击 距离第一次点击时间过长 那么将第二次点击看为第一次点击
			if (firstClick != 0 && System.currentTimeMillis() - firstClick > 300) {
				count = 0;
			}
			count++;
			if (count == 1) {
				firstClick = System.currentTimeMillis();
			} else if (count == 2) {
				lastClick = System.currentTimeMillis();
				// 两次点击小于300ms 也就是连续点击
				if (lastClick - firstClick < 300) {// 判断是否是执行了双击事件
					System.out.println(">>>>>>>>执行了双击事件");

				}
			}
			break;
		case MotionEvent.ACTION_MOVE:
			break;
		case MotionEvent.ACTION_UP:
			break;
		}
		return true;
	}

}


2.main_activity.xml实现:

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/ontourch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>


好了实现就是这么简单;有问题可以@我

原文地址:https://www.cnblogs.com/pangblog/p/3397817.html