我如何使一个Textview的背景大约20%透明(不完全透明),在哪里有一个颜色的背景(即白色)?
当前回答
使颜色在alpha通道中占80%。例如,对于红色,使用#CCFF0000:
<TextView
...
android:background="#CCFF0000" />
在本例中,CC为255 * 0.8 = 204的十六进制数。注意,前两个十六进制数字是用于alpha通道的。格式为#AARRGGBB,其中AA为alpha通道,RR为红色通道,GG为绿色通道,BB为蓝色通道。
我假设20%透明意味着80%不透明。如果你的意思是另一种方式,用33代替CC,这是255 * 0.2 = 51的十六进制。
为了计算alpha透明度值的正确值,您可以遵循以下步骤:
Given a transparency percentage, for example 20%, you know the opaque percentage value is 80% (this is 100-20=80) The range for the alpha channel is 8 bits (2^8=256), meaning the range goes from 0 to 255. Project the opaque percentage into the alpha range, that is, multiply the range (255) by the percentage. In this example 255 * 0.8 = 204. Round to the nearest integer if needed. Convert the value obtained in 3., which is in base 10, to hexadecimal (base 16). You can use Google for this or any calculator. Using Google, type "204 to hexa" and it will give you the hexadecimal value. In this case it is 0xCC. Prepend the value obtained in 4. to the desired color. For example, for red, which is FF0000, you will have CCFF0000.
你可以看看Android的颜色文档。
其他回答
我建议使用alpha属性。
<TextView
android:alpha="0.8" />
或者现在你可以使用选择器。在colors包中创建background_color_25.xml。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:alpha="0.8" android:color="@color/background_color" />
</selector>
用法如下:
<TextView
android:background="@color/background_color_25" />
如果你想用kotlin制作50%透明的颜色,
val percentage = 50f/100 //50%
ColorUtils.setAlphaComponent(resources.getColor(R.color.whatEverColor), (percentage * 255).toInt())
我知道,这是个很老的问题。
如果你想使用颜色值,你也可以使用#ARGB的简短版本。其中A是alpha通道的值。
在白色的情况下,有以下透明度值:
#FFFF - 0%
#EFFF - 6,7%
#DFFF - 13,3%
#CFFF - 20,0%
#BFFF - 26,7%
#AFFF - 33,3%
#9FFF - 40,0%
#FFF8 - 46,7%
#7FFF - 53,3%
#6FFF - 60,0%
#5FFF - 66,7%
#4FFF - 73,3%
#3FFF - 80,0%
#2FFF - 86,7%
#1FFF - 93,3%
#0FFF - 100,0%
所以你可以为TextView添加以下行20%的透明度:
<TextView
android:background="#CFFF"
... />
你可以尝试这样做:
textView.getBackground().setAlpha(51);
这里你可以将不透明度设置在0(完全透明)到255(完全不透明)之间。51就是你想要的20%
在Kotlin中,你可以像这样使用alpha,
//Click on On.//
view.rel_on.setOnClickListener{
view.rel_off.alpha= 0.2F
view.rel_on.alpha= 1F
}
//Click on Off.//
view.rel_off.setOnClickListener {
view.rel_on.alpha= 0.2F
view.rel_off.alpha= 1F
}
结果如屏幕截图所示。
希望这对你有所帮助。谢谢
推荐文章
- 如何在TextView中添加一个子弹符号?
- PreferenceManager getDefaultSharedPreferences在Android Q中已弃用
- 在Android Studio中创建aar文件
- 修改抽射超时时间
- 如何通过数据从第二个活动到第一个活动时按回?——安卓
- 如何在android中获得当前前景活动上下文?
- 如何在Android中获取当前日期?
- 获取Android设备名称
- 在WebView中上传文件
- 加载HTML文件到WebView
- Android:为什么视图没有maxHeight ?
- 如何获得具有已知资源名称的资源id ?
- 在Android上将字符串转换为整数
- 为什么“System.out。”println“工作在Android?
- WebView显示err_cleartext_not_allowed尽管站点是HTTPS