Android CompoundButton Switch jumpDrawablesToCurrentState null crash

南笙酒味 提交于 2019-12-23 18:42:44

问题


I have an app that successfully uses ToggleButton. I am converting the app for use on JELLY BEAN (4.1.1). 4.1.1 has Switch widget which is a better-looking ToggleButton widget. Both widgets derive from CompoundButton.

Android's comparison documentation is here:

http://developer.android.com/guide/topics/ui/controls/togglebutton.html

It says:

The ToggleButton and Switch controls are subclasses of CompoundButton and function in the same manner, so you can implement their behavior the same way.

So what I've done is taken my activity layout file containing ToggleButtons, copied it to the directory res/layout-v14/ and replaced all instances of ToggleButton with Switch. This means Android versions 14 and above will use the layout file with Switch, below 14 will use the layout file with ToggleButton. The XML is identical in each, other than the widget name.

<Switch
 android:id="@+id/settings_some_option_on_off"
 android:textOn="@string/settings_toggle_on"
 android:textOff="@string/settings_toggle_off"
 android:gravity="center"
 android:paddingRight="@dimen/size_padding_minor"
 android:layout_weight="1"
 android:layout_gravity="center"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"/>

In my .java code I'm using CompoundButton only. Not using ToggleButton or Switch at all.

private CompoundButton mViewSomeOptionOnOff;
...
mViewSomeOptionOnOff = (CompoundButton) findViewById(R.id.settings_some_option_on_off);
etc.

When I run on < 14, it works great. Same as before. I get the ToggeButton. When I run on 14, I get a null crash in the Android widget framework.

I downloaded the Android source. From the crash backtrace, I know exactly where the crash is. Switch.java:

808     @Override
809     public void jumpDrawablesToCurrentState() {
810         super.jumpDrawablesToCurrentState();
811         mThumbDrawable.jumpToCurrentState();    <------ boom
812         mTrackDrawable.jumpToCurrentState();
813     }

thumb is a new property to Switch. Even so, I shouldn't have to define it, right? It's not listed as a mandatory property.

Just as a test, back in my -v14 layout, I set android:thumb to a drawable. Then I hit null on line 812, the track. I set android:track to a drawable, and the crash is gone. So what's going on?

Why am I hitting the null crash?

Do I need to find the default Track and Thumb drawables, and copy them in to my app?

Is what I'm trying to do -- using ToggleButton and Switch -- not possible?


回答1:


make sure your minSdkVersion is 14 on AndroidManifest.xml




回答2:


i had this error as well and solved it by setting theme for api 14 and above - as nandeesh commented.



来源:https://stackoverflow.com/questions/12757478/android-compoundbutton-switch-jumpdrawablestocurrentstate-null-crash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!