Is it possible to simulate a click on the screen in Android? [duplicate]

房东的猫 提交于 2020-01-13 03:41:08

问题


Is it possible to simulate a "click" (touch screen) by coordinates or on a view element?


回答1:


It is possible to simulate touch events on android screen. If you have the coordinates of the view then you can generate touch events by using adb shell commands. For e.g-

adb shell input tap x y

where x and y are your coordinates. You can run this command from terminal. If you want to run the command from android code then use "/system/bin/ input tap x y" and run this by using Runtime.getRuntime() method. For details please reply, happy to help! :)




回答2:


presumably you have something that you wish to invoke via a click. So... if it's an actual button you can call performClick() on it. If it's not a button, then just call whatever the method you wish to execute is, when the conditions that you expect are met. It might help if you offered a little more details as to what you're actually trying to do.




回答3:


As azdev suggests, try this:

    view.setOnTouchListener(new OnTouchListener()
{
    public boolean onTouch(View v, MotionEvent event)
    {
        Toast toast = Toast.makeText(
            getApplicationContext(), 
            "View touched", 
            Toast.LENGTH_LONG
        );
        toast.show();

        return true;
    }
});


// Obtain MotionEvent object
long downTime = SystemClock.uptimeMillis();
long eventTime = SystemClock.uptimeMillis() + 100;
float x = 0.0f;
float y = 0.0f;
// List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
int metaState = 0;
MotionEvent motionEvent = MotionEvent.obtain(
    downTime, 
    eventTime, 
    MotionEvent.ACTION_UP, 
    x, 
    y, 
    metaState
);

// Dispatch touch event to view
view.dispatchTouchEvent(motionEvent);



回答4:


On a View, yes. By coordinates, a la Java Robot, not that I'm aware.

For example:

Button buttonFoo = (Button)findViewById(R.id.button_foo);
buttonFoo.performClick();


来源:https://stackoverflow.com/questions/16647431/is-it-possible-to-simulate-a-click-on-the-screen-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!