How to simulate a button click using code?


Question

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.

Same Problem I am Facing

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

Button code:

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

But I want to call that function OnLoadLayout without OnClickEvent

1
204
5/21/2016 3:37:43 PM

Accepted Answer

there is a better way.

View.performClick();

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

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

428
11/9/2013 6:57:58 AM

Just to clarify what moonlightcheese stated: To trigger a button click event through code in Android provide the following:

buttonName.performClick();

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon