贴一下关键报错信息,方便有问题的童鞋搜索
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x2/d=0x7f010009 a=-1}
这里主要讨论attr属性问题,所以主题切换我随手写了个比较简单的。(解决方案在文章末尾)
问题
在Android5.0一下的系统在xml中使用?attr/button_bg的方式指定颜色的时候会导致crash,我们先来看demo。
我写了两套主题,一套日间模式和一套夜间模式,然后通过setTheme来切换。
demo
styles.xml
@color/colorPrimary
@color/colorPrimaryDark
@color/colorAccent
#ffffff
#181818
#000000
#123456
#123456
attr.xml
activity_main.xml
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/appbarBg">
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="100dp"
android:onClick="changeTheme"
android:background="@drawable/button_bg"
android:text="切换主题" />
button_bg.xml
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(Util.THEME);
setContentView(R.layout.activity_main);
}
public void changeTheme(View view) {
Util.THEME = Util.THEME == R.style.AppTheme_Day? R.style.AppTheme_Night: R.style.AppTheme_Day;
recreate();
}
}
demo在Android5.0以上跑是没有问题的
但是5.0以下会打开app会直接报错
问题出在文件button_bg.xml上面
这一句导致的报错
原因:attr属性在5.0以前不支持直接在shape,selector等drawable文件里面使用。
解决方案:
分别写两个drawable文件,然后在attr文件中注册对应的属性,然后在通过style里面的主题来分别定义两个drawable。
新建两个drawable
button_bg_light.xml
button_bg_night.xml
attr.xml 加一句
style.xml
@color/colorPrimary
@color/colorPrimaryDark
@color/colorAccent
#ffffff
button_bg_light
#181818
#000000
#123456
#123456
button_bg_night
activity_main.xml
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="100dp"
android:onClick="changeTheme"
android:background="?attr/button_bg"
android:text="切换主题" />
这样就避免了在drawable文件里面引用attr属性导致的报错问题。
ps:如果还有问题可以加qq群:295456349