android - Crash when clicking button with custom theme -
i creating custom theme button , using android:onclick event of button xml handle click of button.
due reason crashing below exception
java.lang.illegalstateexception: not find method myonclick(view) in activity class android.view.contextthemewrapper onclick handler on view class android.widget.button id 'button1'
and working fine if remove theme attribute button, below theme button
<style name="buttontheme" parent="@android:style/widget.button"> <item name="android:textcolor">#ff0000</item> <item name="android:shadowcolor">#ff000000</item> </style> and button defined in xml below,
<button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textview1" android:layout_margin="20dp" android:onclick="myonclick" android:theme="@style/buttontheme" android:text="button" /> here java code well,
public void myonclick(view view) { switch (view.getid()) { case r.id.button1: getwindow().setstatusbarcolor(getresources() .getcolor(r.color.statusbarcolor)); getwindow().setnavigationbarcolor(getresources() .getcolor(r.color.statusbarcolor)); break; default: break; } } so, reason crashing? able handle click event if remove android:theme="@style/buttontheme" attribute button widget xml.
i've never seen applying android:theme attribute individual view, after bit of googling found out indeed possible, since android 5.0.
a hint of can seen @ end here.
and more detail here.
as second link explains, contextthemewrapper used modify theme associated base context. however, since activity need hold on own theme, can imagine new contextthemewrapper created , assigned new context of view. since new context not activity more, callback functions don't exist here , error describe.
you can use debugger prove (i used android studio, can use ide of choice, details might different).
- run app in debug mode
themeattribute set. - when exception, stacktrace contain reference
viewclass invokesonclick. - use add breakpoint before exception occurs.
- now run app again in debug mode, click button
- when hit breakpoint evaluate expression
getcontext(). see returns object of typecontextthemewrapper, have membermbasepoints actualactivity,getcontext()not returnactivity, not have callback functions defined onactivity. - now remove
themeattribute, leave breakpoint , run app again. - when hit breakpoint, evaluate expression
getcontext()again , see time returnsactivitydirectly, why callbacks work, if don't setthemeattribute.
in short, seems can't use android:onclick attribute if want make use of new feature, , have manually assign onclicklistener described here
Comments
Post a Comment