安卓OnTouchListener模拟长按事件,上滑事件,下滑事件
最近在做一个安卓项目的时候,需要经常用到OnTouchListener监听器,并且需要各种手势的识别,长按事件是最频繁使用的。但苦于安卓没有提供OnTouchListener的长按事件,只提供了基础的按下和抬起事件,无奈之下,自己通过按下和抬起事件写了一套事件,包括长按事件、上滑事件、下滑事件。话不多说,看实现代码。
为了方便演示,先用一个空白的TextView接收操作事件——MotionEvent
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/test" />
</LinearLayout>
然后就是代码部分了,放在下面,很容易读懂,开盖即食(不愿读的话就直接搬走,在对应部分修改自己要执行的操作就好)
public class test extends BaseActivity implements View.OnTouchListener {
int LONG_CLICK_TIME = 1500;
TextView textView;
long time = 0;
boolean isLongClick = false;
boolean stoped = false;
double before_press_Y;
StringBuilder builder = new StringBuilder();
class MyThread extends Thread {
public void run() {
System.out.println("---------------开始计时-------------------");
while (System.currentTimeMillis() - time < LONG_CLICK_TIME && !stoped) ;
if (stoped) return;
System.out.println("-----------------长按事件发生-----------------");
isLongClick = true;
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(test.this, "长按事件", Toast.LENGTH_SHORT).show();
//处理长按事件///
builder.append("长按事件\n");
textView.setText(builder);
///
}
});
}
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
textView = findViewById(R.id.test);
textView.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
System.out.println("---------------按下了-------------------");
stoped = false;
before_press_Y = event.getY();
time = System.currentTimeMillis();
new MyThread().start();
break;
case MotionEvent.ACTION_UP:
System.out.println("--------------抬起了------------------");
stoped = true;
if (isLongClick) {
System.out.println("-----------------长按事件,不处理---------------");
isLongClick = false;
return true;
}
double now_press_Y = event.getY();
if (now_press_Y - before_press_Y > 50) {
/处理下拉事件///
System.out.println("-------------------下拉事件----------------------");
builder.append("下拉事件\n");
} else if (now_press_Y - before_press_Y == 0) {
处理单击事件/
System.out.println("-------------------处理单击事件----------------------");
builder.append("单击事件\n");
} else if (before_press_Y - now_press_Y > 50) {
处理上拉事件/
System.out.println("-------------------上滑事件----------------------");
builder.append("上滑事件\n");
}
textView.setText(builder);
break;
}
return true;
}
}
之间网上搜了很久没发现有可靠的代码,靠人不如靠己啊。