如何使用代码模拟按钮单击? [英] How to simulate a button click using code?

查看:94
本文介绍了如何使用代码模拟按钮单击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Android中的代码触发按钮点击事件?我想在发生其他事件时以编程方式触发按钮单击.

How can I trigger a button click event using code in Android? I want to trigger the button click programmatically when some other event occurs.

我正面临同样的问题

public void onDateSelectedButtonClick(View v){
    /*Something  Alarm Management 
    http://www.java2s.com/Code/Android/Core-Class/Alarmdemo.htm
    copied code from this site*/
}

按钮代码:

<Button
    android:onClick="onDateSelectedButtonClick"
    android:text="Set notification for this date" />

但是我想在没有OnClickEvent的情况下调用该函数OnLoadLayout

But I want to call that function OnLoadLayout without OnClickEvent

推荐答案

还有一种更好的方法.

View.performClick();

http://developer.android.com/reference/android/view/View.html#performClick()

这应该回答您所有的问题.每个View都会继承此功能,包括Button,Spinner等.

this should answer all your problems. every View inherits this function, including Button, Spinner, etc.

请澄清一下,View没有静态的performClick()方法.您必须在View实例上调用performClick(). 例如,您不能只拨打

Just to clarify, View does not have a static performClick() method. You must call performClick() on an instance of View. For example, you can't just call

View.performClick();

相反,请执行以下操作:

Instead, do something like:

View myView = findViewById(R.id.myview);
myView.performClick();

这篇关于如何使用代码模拟按钮单击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆