簡體   English   中英

如何將字符串顏色更改為顏色資源?

[英]How to change string color into color resource?

我想更改標題背景顏色,並且正在使用 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

從您的字符串創建 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();

將顏色十六進制代碼保存在 colors.xml 中,如下所示:#AABBEE(在此處使用顏色的十六進制代碼)然后,設置背景:

  .withHeaderBackground(R.color.myColor)
  .withSelectionListEnabledForSingleProfile(false)
  ....

首先,您應該在問題中提到您使用的是MaterialDrawer庫,因為AccountHeader不是標准 Android SDK 的一部分。

這就是說,檢查的源AccountHeaderBuilder在回購表明,存在用於3種變體withHeaderBackground方法,即采取Drawable ,一個@DrawableRes int和一個ImageHolder分別。

如果您堅持從strings.xml加載顏色,那么我認為以下方法可行:

使用您的字符串創建一個ColorDrawable ,其格式應為0xAARRGGBB

由於ColorDrawable類擴展了Drawable ,它應該是withHeaderBackground方法的有效參數。 您的代碼如下所示:

ColorDrawable cd = new ColorDrawable(getResources().getString(R.string.default_color));

AccountHeader headerResult = new AccountHeaderBuilder()
            .withActivity(this)                   
  .withHeaderBackground(cd)
  .withSelectionListEnabledForSingleProfile(false)
            ... and so on 

一種更簡單的方法是簡單地擁有一個drawable資源並將其用作R.drawable.default_drawable代替。

Color.parseColor()解析顏色字符串,並返回對應的color-int ,這個 int 值與資源 ID不同,即使兩個值也是int類型。

你可以這樣做:

int colorID =
    getResourceID("your_color_name", "color", getApplicationContext());

不需要使用Color.parseColor()方法。

您正在使用的withHeaderBackground()的簽名是這樣的:

public AccountHeaderBuilder withHeaderBackground(@DrawableRes int headerBackgroundRes)

但是您傳遞的是某種顏色的int值。
您需要一個顏色或可繪制資源 ID。

您可以分兩步完成

假設你有一種顏色 #8080000

1. 先將你的 Hex 轉換成 int

int yourColor = Color.parseColor("#808000");

2.設置背景

.setBackgroundColor(context.getColor(yourColor));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM