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

我也面临着同样的问题

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" />

但我想叫那个函数OnLoadLayout而不叫OnClickEvent


当前回答

只是为了澄清月光奶酪所说的: 在Android中通过代码触发按钮点击事件 提供以下资料:

buttonName.performClick();

其他回答

从API15开始,您还可以使用callOnClick()直接调用附加视图OnClickListener。与performClick()不同,这只调用侦听器,而不执行任何相关的单击操作,例如报告可访问性事件。

有更好的办法。

View.performClick();

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

这应该能解决你所有的问题。每个视图都继承这个函数,包括按钮,旋转器等。

澄清一下,View没有静态的performClick()方法。必须在View的实例上调用performClick()。 例如,你不能只是打电话

View.performClick();

相反,你可以这样做:

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

你可以这样做

private Button btn;
btn = (Button)findViewById(R.id.button2);
btn.performClick();

只是为了澄清月光奶酪所说的: 在Android中通过代码触发按钮点击事件 提供以下资料:

buttonName.performClick();

只需写这一行简单的代码:-

button.performClick();

其中button是button类的引用变量,定义如下:-

private Button buttonToday ;
buttonToday = (Button) findViewById(R.id.buttonToday);

就是这样。