android 多个属性,Android 多个主题切换使用attr属性导致报错问题分析

贴一下关键报错信息,方便有问题的童鞋搜索

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值