How to simulate a button click using code?

后端 未结 7 1052
庸人自扰
庸人自扰 2020-12-04 05:27

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 Fac

相关标签:
7条回答
  • 2020-12-04 06:06

    you can do it this way

    private Button btn;
    btn = (Button)findViewById(R.id.button2);
    btn.performClick();
    
    0 讨论(0)
  • 2020-12-04 06:12

    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.

    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();
    
    0 讨论(0)
  • 2020-12-04 06:15

    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.

    0 讨论(0)
  • 2020-12-04 06:18

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

    buttonName.performClick();
    
    0 讨论(0)
  • 2020-12-04 06:25

    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.

    0 讨论(0)
  • 2020-12-04 06:25

    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().

    0 讨论(0)
提交回复
热议问题