您的位置:首页 > 移动开发 > Android开发

android onClick方法改造实现双击事件

2014-06-07 22:59 615 查看
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
// 是否第二次点击标志
private boolean flag = true;
// 第一次点击时间
private long one = 0;
// 第二次点击时间
private long two = 0;
// 算为双击点击时间间隔
private int interval = 500;</span>

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

public void twoTouch(View v) {
// Log.i(TAG, "进入 twoTouch");
// 判断是否第二次点击
if (!flag) {
// 取第二次时间时超时,重置标志之类
if ((System.currentTimeMillis() - one) > interval) {
flag = true;
one = 0;
two = 0;
}
}
// 判断标志给 one two 赋值,初始 true 给 one 赋值
if (flag) {
Log.i(TAG, "one 赋值");
one = System.currentTimeMillis();
flag = false;
Toast.makeText(getApplicationContext(), "第一次点击!",
Toast.LENGTH_SHORT).show();
} else {
Log.i(TAG, "two 赋值");
two = System.currentTimeMillis();
if ((two - one) > interval) {
// 取第二次时间时超时
flag = true;
one = 0;
two = 0;
}
}
// 计算两次点击间隔
long t_o = two - one;
// 判断间隔是否在双击范围中
if (t_o > 0 && t_o < interval) {
Log.i(TAG, "双击发生");
// 双击发生则设置标志之类复位
flag = true;
one = 0;
two = 0;
// 对话框构建器
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
// 设置标题、内容
dialog.setTitle("提示");
dialog.setMessage("你双击了哈!!!");
// 设置不能使用 back 键关闭
dialog.setCancelable(false);
// 设置左边按钮
dialog.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Toast.makeText(getApplicationContext(),
// "点击了对话框确定钮!", Toast.LENGTH_SHORT).show();
}
});
dialog.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Toast.makeText(getApplicationContext(),
// "点击了对话框取消钮!", Toast.LENGTH_SHORT).show();
}
});
// 创建对话框
AlertDialog alert = dialog.create();
// 显示对话框
alert.show();
} else if (two > 0 && !flag) {
Log.i(TAG, "双击没有发生");
// 双击没有发生设置标志之类复位
flag = true;
one = 0;
two = 0;
}
}
}

标红为主要代码,全局变量中定义:是否第二次点击标志,第一次点击时间,第二次点击时间

首先判断是否第二次点击防止了,先点击一次,等会连续点击两次的问题。

欢迎交流哈

学习笔记:

布局文件中使用TextView控件 声明点击事件,必须声明 android:clickable="true"

    <TextView

        android:id="@+id/tv"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:background="#0f0"
        android:clickable="true"

        android:gravity="center"
        android:onClick="twoTouch"

        android:text="@string/hello_world"

        android:textSize="30sp" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息