java 以编程方式模拟Android按钮点击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15579976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:08:30  来源:igfitidea点击:

Simulate Android button click programmatically

javaandroid

提问by EGHDK

I've seen thisroute,

我见过条路,

View.performClick();

but it doesn't show the actual press of the button. I've also tried thismethod,

但它没有显示按钮的实际按下。这个方法我也试过

btn.setPressed(true);
btn.invalidate();

but, it just shows the button being pressed down. I've narrowed it down to this code, which presses down, and releases, but doesn't click. Am I missing something? How can I do a complete click as if though the user was clicking (monkeyrunner is not an option as of right now)

但是,它只显示按钮被按下。我把它缩小到这个代码,它按下并释放,但不点击。我错过了什么吗?我如何进行完整的点击,就好像用户正在点击一样(monkeyrunner 目前不是一个选项)

btn = (Button) findViewById(R.id.btn_box);
    Handler handler = new Handler();
    Runnable r = new Runnable() {
        public void run() {
            btn.setPressed(true);
            btn.invalidate();
            Handler handler1 = new Handler();
            Runnable r1 = new Runnable() {
                public void run() {
                    btn.setPressed(false);
                    btn.invalidate();

                }
            };
            handler1.postDelayed(r1, 1000);

        }
    };
    handler.postDelayed(r, 1000);

回答by stinepike

Your code is fine. just add btn.performClick();after the invalidate();

你的代码没问题。只需在btn.performClick();之后添加 invalidate();

And for better look you can reduce the time of handler1.

为了更好看,您可以减少handler1.