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:onClickno longer works, because the program will look for the click handler fromContextThemeWrapperinstead 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 anActivityinto aFragment, they may be ignoring this problem. - To make the two problems above more severe,
onClickuses 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:onClickattribute, but noandroid:onChangeor 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.