項目需求:
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="https://schemas.android.com/apk/res/android" xmlns:tools="https://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>