[英]how to set opacity on a button with a transparent background color programmatically
我正在開發一個組件庫,目前正在開發按鈕組件,但是當涉及到具有透明背景顏色的禁用按鈕時,我遇到了問題,android 只是將灰色設置為按鈕的背景顏色。
在這里我設置顏色
typeStyles.put("defaultBackgroundColor", context.getResources().getColor(R.color.color_transparent));
在這里我恢復顏色
this.mDefaultBackgroundColor = buttonType.styles.get("defaultBackgroundColor");
我有幾種類型的按鈕,所以每個按鈕都有不同的配置。
導致我出現問題的按鈕如下
圖像按鈕是一個禁用 state 並具有透明背景的按鈕,問題在於它在按鈕上設置了灰色。
在這里我設置不透明度。
int mColor = mDefaultBackgroundColor;
byte factor = 125;
float alpha = getResources().getFloat(R.dimen.opacity_intense);
float2ByteArray(alpha);
int color = (factor << 24) | (mColor & 0x00ffffff);
disabledDrawable.setColor(color);
disabledDrawable.setStroke(mBorderWidth, mDefaultBackgroundColor);
if (!mEnabled)
this.setAlpha(.5f);
在材料組件庫中,這是一種方法(它至少需要版本1.2.0-beta01
):
MaterialColors.compositeARGBWithAlpha(color, alpha);
否則,您可以使用androidx.core.graphics.ColorUtils
class:
ColorUtils.setAlphaComponent(originalARGB, alpha);
例子:
int color = ColorUtils.setAlphaComponent(
ContextCompat.getColor(this,R.color....),xx);
int color = MaterialColors.compositeARGBWithAlpha(
ContextCompat.getColor(this,R.color....),xx);
我終於設法解決了這個問題。 我修改了下面的代碼行。
int mColor = mDefaultBackgroundColor;
int color = mColor;
disabledDrawable.setColor(color);
disabledDrawable.setStroke(mBorderWidth, mBorderColor);
if (!mEnabled)
this.setAlpha(.5f);
之前是這樣
int mColor = mDefaultBackgroundColor;
byte factor = 125;
float alpha = getResources().getFloat(R.dimen.opacity_intense);
float2ByteArray(alpha);
int color = (factor << 24) | (mColor & 0x00ffffff);
disabledDrawable.setColor(color);
disabledDrawable.setStroke(mBorderWidth, mDefaultBackgroundColor);
if (!mEnabled)
this.setAlpha(.5f);
這是結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.