Why you should never use android:onClick XML attribute
Recently, I made a decision to disallow programmers to use android:onClick
XML attributes to add click event listeners. Existing usages will be removed too. Actually, the attribute itself was a very bad design, considering that web frontend developers has switched from onclick
HTML attribute to addEventListener
API for a long time.
Here are the real reasons why android:onClick
XML attribute should be avoided:
- If an ancestor element has theme applied,
android:onClick
no longer works, because the program will look for the click handler fromContextThemeWrapper
instead ofActivity
(see http://stackoverflow.com/questions/29525644/). When applying a theme, programmers may not realize the problem. - Android look for the specified method from the parent
Activity
. When programmers change anActivity
into aFragment
, they may be ignoring this problem. - To make the two problems above more severe,
onClick
uses reflection. It therefore prevents the compiler from telling you problems. You app will crash at run time. - As it uses reflection, performance will be compromised.
- Android provides
android:onClick
attribute, but noandroid:onChange
or any other XML attributes for event listeners. Considering click listeners aren't really different from other event listeners, keeping them consistent will be good. - When using
android:onClick
, one must create a public method with parameter(View view)
. Android Lint will then complain "unused parameter". - Adding a public method is not elegant in any way.