Skip to content
Fix Code Error

How to make a background 20% transparent on Android

March 13, 2021 by Code Error
Posted By: Anonymous

How do I make the background of a Textview about 20% transparent (not fully transparent), where there is a color in the background (i.e. white)?

Solution

Make the color have 80% in the alpha channel. For example, for red use #CCFF0000:

<TextView
   ...
   android:background="#CCFF0000" />

In the example, CC is the hexadecimal number for 255 * 0.8 = 204. Note that the first two hexadecimal digits are for the alpha channel. The format is #AARRGGBB, where AA is the alpha channel, RR is the red channel, GG is the green channel and BB is the blue channel.

I’m assuming that 20% transparent means 80% opaque. If you meant the other way, instead of CC use 33 which is the hexadecimal for 255 * 0.2 = 51.

In order to calculate the proper value for an alpha transparency value you can follow this procedure:

  1. Given a transparency percentage, for example 20%, you know the opaque percentage value is 80% (this is 100-20=80)
  2. The range for the alpha channel is 8 bits (2^8=256), meaning the range goes from 0 to 255.
  3. 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.
  4. 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.
  5. Prepend the value obtained in 4. to the desired color. For example, for red, which is FF0000, you will have CCFF0000.

You can take a look at the Android documentation for colors.

Answered By: Anonymous

Related Articles

  • Creating nested dicts with dynamic key and values
  • ListView inside ScrollView is not scrolling on Android
  • Android : Fragment doesn't fit into Fragment Container
  • Android adding simple animations while…
  • Android Layout Animations from bottom to top and top to…
  • Web colors in an Android color xml resource file
  • How to configure Ubuntu as router in Vagrant
  • How to use hex color values
  • How to implement HorizontalScrollView like Gallery?
  • Create ID when exploding dataframe

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to set the current working directory?

Next Post:

.gitignore is ignored by Git

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error