Crash When Clicking Button With Custom Theme
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).
- Run the app in debug mode with
theme
attribute set. - When you get the exception, the stacktrace will contain a reference to the
View
class where it invokesonClick
. - Use this to add a breakpoint before the exception occurs.
- Now run the app again in debug mode, click the button
- When you hit the breakpoint evaluate the expression
getContext()
. You will see that this returns an object of typeContextThemeWrapper
and it will have a membermBase
which points back to your actualActivity
, sogetContext()
itself does not return yourActivity
and does not have the callback functions you defined on yourActivity
. - Now remove the
theme
attribute, leave the breakpoint and run the app again. - When you hit the breakpoint, evaluate the expression
getContext()
again and you will see that this time it returns yourActivity
directly, which is why your callbacks work, if you don't set thetheme
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"