Born again shelter - xml
type: channel
link: https://bash.kmxz.net/tag/xml/
items: Why you should never use android:onClick XML attribute

Why you should never use android:onClick XML attribute
type: item
date: 2016-05-19T07:52:00+00:00
description: 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 from ContextThemeWrapper instead of Activity (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 an Activity into a Fragment, 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 no android: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.