How to simulate a button click using code?

2019-03-07 11:10发布

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

7条回答
何必那么认真
2楼-- · 2019-03-07 11:37

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.

查看更多
淡お忘
3楼-- · 2019-03-07 11:37

you can do it this way

private Button btn;
btn = (Button)findViewById(R.id.button2);
btn.performClick();
查看更多
smile是对你的礼貌
4楼-- · 2019-03-07 11:42

Android's callOnClick() (added in API 15) can sometimes be a better choice in my experience than performClick(). If a user has selection sounds enabled, then performClick() could cause the user to hear two continuous selection sounds that are somewhat layered on top of each other which can be jarring. (One selection sound for the user's first button click, and then another for the other button's OnClickListener that you're calling via code.)

查看更多
三岁会撩人
5楼-- · 2019-03-07 11:44

If you do not use the sender argument, why not refactor the button handler implementation to separate function, and call it from wherever you want (from the button handler and from the other place).

Anyway, it is a better and cleaner design - a code that needs to be called on button handler AND from some other places deserves to be refactored to own function. Plus it will help you separate UI handling from application logic code. You will also have a nice name to the function, not just onDateSelectedButtonClick().

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-03-07 11:48

Just write this simple line of code :-

button.performClick();

where button is the reference variable of Button class and defined as follows:-

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

That's it.

查看更多
ゆ 、 Hurt°
7楼-- · 2019-03-07 11:50

Starting with API15, you can use also callOnClick() that directly call attached view OnClickListener. Unlike performClick(), this only calls the listener, and does not do any associated clicking actions like reporting an accessibility event.

查看更多
登录 后发表回答