Reputation: 77
I'm playing with Android and I'd like to know if there's any way to invoke a listener call programmatically, for example, having an onClick()
listener and invoke a call to this listener without touching the screen when the activity is created.
Upvotes: 5
Views: 8060
Reputation: 47945
There is no way to get the set OnClickListener
. So you need to store it and call your OnClickListener
directly.
OnClickListener store = new OnClickListener() {/*...*/};
view.setOnClickListener(store);
store.onClick(view);
Upvotes: 6
Reputation: 93842
Never tried that, but after assigning a clickListener
to your object (for example a Button
), call on your onCreate
method myButton.performClick()
.
Android doc :
public boolean performClick ()
Added in API level 1
Call this view's OnClickListener, if it is defined. Performs
all normal actions associated with clicking: reporting accessibility event,
playing a sound, etc.
Returns
True there was an assigned OnClickListener that was called,
false otherwise is returned.
Upvotes: 6
Reputation: 20063
Although this is possible, I'd actually advise against it. Listeners should be called from the UI but the business logic behind it is what should actually be called directly. This would provide "separation of concern" between both layers.
You should be calling the code that the listener calls in it's onClick
method rather than invoking the onClick
directly.
Upvotes: 0