2016-08-10 87 views
0

我知道我可以通過在十六進制(#AARRGGBB)中添加一個alpha通道來設置不透明度,但是如果我想使用我的colors.xml中的值,否則我不想添加不透明度?如何在顏色資源上設置不透明度?

例如,我用#074EB2深藍色在我colors.xml,因爲這樣的:

<color name="DarkBlue">#074EB2</color> 

現在,我有一個自定義按鈕的背景帶邊框。我希望邊框使用這種深藍色,但添加了不透明度。按鈕看起來像這樣:

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
android:shape="rectangle"> 
    <stroke android:width="1dp" android:color="@color/DarkBlue"/> 
    <corners android:radius="2dp"/> 
</shape> 

如何添加不透明度?我需要爲不透明度的colors.xml添加一個新值嗎?即,<color name="DarkBlueTransparent">#80074EB2</color>?我看到的問題是它不具有可伸縮性 - 如果我有其他需要這種顏色80%不透明度的地方呢? 90%?我的colors.xml文件會以不同的值爆炸,以獲得我想要的東西的透明度。

+0

要麼創造更多資源,要麼將容器的不透明度設置爲任何需要的值。 – Shaishav

+0

「我的colors.xml文件會以不同的值爆炸,以獲得我想要的東西的透明度。」真?你真的需要這麼多的透明度以各種顏色?像DarkBlue70Percent和DarkBlue71Percent? – Salem

+0

過分誇張,但你明白了。 –

回答

1

你不能在xml中做動態不透明。但是你可以在java端動態地應用alpha。

使用此方法將Alpha應用於您的顏色。

public static int getColorWithAlpha(int yourColor, int alpha) { 
    int red = Color.red(yourColor); 
    int blue = Color.blue(yourColor); 
    int green = Color.green(yourColor); 
    return Color.argb(alpha, red, green, blue); 
} 
現在

通過調用方法

blueWithAlpha = getColorWithAlpha(darkBlue, 120); 

120獲得阿爾法的顏色是你的阿爾法水平

Alpha水平應該是介於0到225

現在將您的顏色應用於您的按鈕

mButton.setBackgroundColor(blueWithAlpha);