Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android模擬點擊的兩種方式

Android模擬點擊的兩種方式

編輯:關於Android編程

導論

在Android中模擬一個點擊事件有兩種方式是通過模擬MotionEvent來實現;一種是通過ADB來實現


第一種:模擬MotionEvent

通用方法如下:

private void setSimulateClick(View view, float x, float y) {
		long downTime = SystemClock.uptimeMillis();
		final MotionEvent downEvent = MotionEvent.obtain(downTime, downTime,
				MotionEvent.ACTION_DOWN, x, y, 0);
		downTime += 1000;
		final MotionEvent upEvent = MotionEvent.obtain(downTime, downTime,
				MotionEvent.ACTION_UP, x, y, 0);
		view.onTouchEvent(downEvent);
		view.onTouchEvent(upEvent);
		downEvent.recycle();
		upEvent.recycle();
	}

Demo:

package com.xys.simulateevent;

import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

	Button button;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button = (Button) findViewById(R.id.button1);
	}

	public void clickeMe(View view) {
		Toast.makeText(this, "clicked", Toast.LENGTH_LONG).show();
	}

	public void simulate(View view) {
		setSimulateClick(button, 160, 100);
	}

	private void setSimulateClick(View view, float x, float y) {
		long downTime = SystemClock.uptimeMillis();
		final MotionEvent downEvent = MotionEvent.obtain(downTime, downTime,
				MotionEvent.ACTION_DOWN, x, y, 0);
		downTime += 1000;
		final MotionEvent upEvent = MotionEvent.obtain(downTime, downTime,
				MotionEvent.ACTION_UP, x, y, 0);
		view.onTouchEvent(downEvent);
		view.onTouchEvent(upEvent);
		downEvent.recycle();
		upEvent.recycle();
	}
}

第二種:ADB控制

ADB中通過input來實現,用於輸入touch,key等事件:
The sources are: 
      trackball
      joystick
      touchnavigation
      mouse
      keyboard
      gamepad
      touchpad
      dpad
      stylus
      touchscreen

The commands and default sources are:
      text  (Default: touchscreen)
      keyevent [--longpress]  ... (Default: keyboard)
      tap   (Default: touchscreen)
      swipe     [duration(ms)] (Default: touchscreen)
      press (Default: trackball)
      roll   (Default: trackball)

Demo 輸入按鍵enter key:
adb shell input keyevent 66

Demo 輸入輸入滑動操作:
adb shell input touchscreen swipe 18 665 18 350





  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved