首页 > 解决方案 > 如何将字符串颜色更改为颜色资源?

问题描述

我想改变我的标题背景颜色,我正在使用 MaterialDrawer 库:

   AccountHeader headerResult = new AccountHeaderBuilder()
            .withActivity(this)                   
  .withHeaderBackground(Color.parseColor(mPrefs.getString("theme_color",getResources().getString(R.string.default_color)))
  .withSelectionListEnabledForSingleProfile(false)
            ... and so on 

但是对于标题背景,我收到错误消息“预期颜色资源 id (R.color.) 但收到一个 RGB 整数”并且无法设置从首选项读取的背景颜色。它在日志上给出错误:“ android.content.res.Resources$NotFoundException: Resource ID #0x2e60e8

标签: androidmaterial-design

解决方案


从您的字符串创建 ColorDrawable,您可以将其设置为您的标题

int col = Color.parseColor(mPrefs.getString("theme_color",getResources().getString(R.string.default_color)));
ColorDrawable cd = new ColorDrawable();
cd.setColor(col);

headerResult = new AccountHeaderBuilder()
            .withActivity(this)
            .withCompactStyle(false)
            .withHeaderBackground(cd)
            .withSavedInstance(savedInstanceState)
            .build();

推荐阅读