Skip to content Skip to sidebar Skip to footer

Crash When Clicking Button With Custom Theme

I am creating a custom theme for button and using android:onClick event of Button from xml itself to handle the click of Button. Due to some reason its crashing with below exceptio

Solution 1:

I've never seen anybody applying the android:theme attribute to an individual View, but after a bit of googling I found out that this is indeed possible, but only since Android 5.0.

A hint of this can be seen at the end here.

And some more detail here.

As the second link explains, a ContextThemeWrapper is used to modify the theme associated with the base Context. However, since your Activity will need to hold on to its own theme, I can only imagine that a new ContextThemeWrapper is created and assigned as the new Context of your View. Since this new Context is not your Activity any more, your callback functions don't exist here and you get the error you describe.

You can use the debugger to prove this yourself (I used Android Studio, but you can probably use the IDE of your choice, the details might be different).

  1. Run the app in debug mode with theme attribute set.
  2. When you get the exception, the stacktrace will contain a reference to the View class where it invokes onClick.
  3. Use this to add a breakpoint before the exception occurs.
  4. Now run the app again in debug mode, click the button
  5. When you hit the breakpoint evaluate the expression getContext(). You will see that this returns an object of type ContextThemeWrapper and it will have a member mBase which points back to your actual Activity, so getContext() itself does not return your Activity and does not have the callback functions you defined on your Activity.
  6. Now remove the theme attribute, leave the breakpoint and run the app again.
  7. When you hit the breakpoint, evaluate the expression getContext() again and you will see that this time it returns your Activity directly, which is why your callbacks work, if you don't set the theme attribute.

In short, it seems like you can't use the android:onClick attribute if you want to make use of this new feature, and you will have to manually assign an OnClickListener as described here

Solution 2:

Sometimes when we add style to Button It affects default android clickable behavior.

Try adding property clickable="true" in <Button... />

Or

You can also add <item name="android:clickable" >true</item> to style of button.

Solution 3:

After spending so much time on this, the thing that worked for me was to apply the theme in code setTheme(R.style.AppToolbar); in the onCreate() instead of ripping out all the android:OnClick from all the layouts.

Post a Comment for "Crash When Clicking Button With Custom Theme"