Cómo hacer un fondo 20% transparente en Android


¿Cómo hago que el fondo de un Textview sea aproximadamente un 20% transparente (no totalmente transparente), donde hay un color en el fondo (es decir, blanco)?

Author: Peter Mortensen, 2012-07-02

14 answers

Haz que el color tenga un 80% en el canal alfa. Por ejemplo, para el uso rojo #CCFF0000:

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

En el ejemplo, CC es el número hexadecimal para 255 * 0.8 = 204. Tenga en cuenta que los dos primeros dígitos hexadecimales son para el canal alfa. El formato es #AARRGGBB, donde AA es el canal alfa, RR es el canal rojo, GG es el canal verde y BB es el canal azul.

Asumo que 20% transparente significa 80% opaco. Si se refería al otro lado, en lugar de CC use 33 que es el hexadecimal para 255 * 0.2 = 51.

Para calcular el valor apropiado para un valor de transparencia alfa puede seguir este procedimiento:

  1. Dado un porcentaje de transparencia, por ejemplo 20%, usted sabe que el valor del porcentaje opaco es 80% (esto es 100-20=80)
  2. El rango para el canal alfa es de 8 bits (2^8=256), lo que significa que el rango va de 0 a 255.
  3. Proyectar el porcentaje opaco en el rango alfa, es decir, multiplicar el rango (255) por el porcentaje. En este ejemplo 255 * 0.8 = 204. Redondea al entero más cercano si es necesario.
  4. Convertir el valor obtenido en 3., que está en base 10, a hexadecimal (base 16). Puede utilizar Google para esta o cualquier calculadora. Usando Google, escriba "204 a hexa" y le dará el valor hexadecimal. En este caso es 0xCC.
  5. Anteponer el valor obtenido en 4. al color deseado. Por ejemplo, para rojo, que es FF0000, tendrás CCFF0000.

Puede echar un vistazo a la Documentación de Android para colores .

 907
Author: aromero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 21:15:44

Utilice el siguiente código para negro:

<color name="black">#000000</color>

Ahora, si quiero usar opacidad, puede usar el siguiente código:

 <color name="black">#99000000</color> <!-- 99 is for alpha and others pairs zero's are for R G B -->

Y más abajo para el código de opacidad: y todo el nivel de opacidad aquí

Valores de Opacidad hexadecimales

100% — FF
95% — F2
90% — E6
85% — D9
80% — CC
75% — BF
70% — B3
65% — A6
60% — 99
55% — 8C
50% — 80
45% — 73
40% — 66
35% — 59
30% — 4D
25% — 40
20% — 33
15% — 26
10% — 1A
5% — 0D
0% — 00

Si siempre se olvida de qué código para la transparencia, entonces debe tener que ver el siguiente enlace y no se preocupe por recordar nada con respecto al código transparente :-

Https://github.com/duggu-hcd/TransparentColorCode

textviewHeader.setTextColor(Color.parseColor(ColorTransparentUtils.transparentColor10(R.color.border_color)));
 1294
Author: duggu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-02 11:32:13

Puede administrar la opacidad del color cambiando los primeros 2 caracteres en la definición de color:

#99000000

100% — FF
99% — FC
98% — FA
97% — F7
96% — F5
95% — F2
94% — F0
93% — ED
92% — EB
91% — E8

90% — E6
89% — E3
88% — E0
87% — DE
86% — DB
85% — D9
84% — D6
83% — D4
82% — D1
81% — CF

80% — CC
79% — C9
78% — C7
77% — C4
76% — C2
75% — BF
74% — BD
73% — BA
72% — B8
71% — B5

70% — B3
69% — B0
68% — AD
67% — AB
66% — A8
65% — A6
64% — A3
63% — A1
62% — 9E
61% — 9C

60% — 99
59% — 96
58% — 94
57% — 91
56% — 8F
55% — 8C
54% — 8A
53% — 87
52% — 85
51% — 82

50% — 80
49% — 7D
48% — 7A
47% — 78
46% — 75
45% — 73
44% — 70
43% — 6E
42% — 6B
41% — 69

40% — 66
39% — 63
38% — 61
37% — 5E
36% — 5C
35% — 59
34% — 57
33% — 54
32% — 52
31% — 4F

30% — 4D
29% — 4A
28% — 47
27% — 45
26% — 42
25% — 40
24% — 3D
23% — 3B
22% — 38
21% — 36

20% — 33
19% — 30
18% — 2E
17% — 2B
16% — 29
15% — 26
14% — 24
13% — 21
12% — 1F
11% — 1C

10% — 1A
9% — 17
8% — 14
7% — 12
6% — 0F
5% — 0D
4% — 0A
3% — 08
2% — 05
1% — 03
0% — 00 
 104
Author: carlol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-24 16:13:26

Use un color con un valor alfa como #33------, y establézcalo como fondo de su EditText usando el atributo XML android:background=" ".

  1. 0% (transparente) -> #00 en hexadecimal
  2. 20% -> #33
  3. 50% -> #80
  4. 75% -> #C0
  5. 100% (opaco) -> #FF

255 * 0.2 = 51 → en hex 33

 91
Author: K_Anas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 21:17:02

Puedes intentar hacer algo como:

textView.getBackground().setAlpha(51);

Aquí puede establecer la opacidad entre 0 (completamente transparente) a 255 (completamente opaco). El 51 es exactamente el 20% que quieres.

 73
Author: yugidroid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-01 22:17:27

En Android Studio hay una herramienta integrada para ajustar el color y el valor alfa/opacidad :

Android Ajustar La Opacidad del Color

 56
Author: Jayakrishnan PM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 21:23:54

Ver captura de pantalla

He tomado tres puntos de vista. En la primera vista establecí el color completo (sin alfa), en la segunda vista establecí el color medio (0.5 alfa), y en la tercera vista establecí el color claro (0.2 alfa).

Puede establecer cualquier color y obtener color con alpha utilizando el siguiente código:

File activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools = "http://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    android:gravity = "center"
    android:orientation = "vertical"
    tools:context = "com.example.temp.MainActivity" >

    <View
        android:id = "@+id/fullColorView"
        android:layout_width = "100dip"
        android:layout_height = "100dip" />

    <View
        android:id = "@+id/halfalphaColorView"
        android:layout_width = "100dip"
        android:layout_height = "100dip"
        android:layout_marginTop = "20dip" />

    <View
        android:id = "@+id/alphaColorView"
        android:layout_width = "100dip"
        android:layout_height = "100dip"
        android:layout_marginTop = "20dip" />

</LinearLayout>

File MainActivity.java

public class MainActivity extends Activity {

    private View fullColorView, halfalphaColorView, alphaColorView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fullColorView = (View)findViewById(R.id.fullColorView);
        halfalphaColorView = (View)findViewById(R.id.halfalphaColorView);
        alphaColorView = (View)findViewById(R.id.alphaColorView);

        fullColorView.setBackgroundColor(Color.BLUE);
        halfalphaColorView.setBackgroundColor(getColorWithAlpha(Color.BLUE, 0.5f));
        alphaColorView.setBackgroundColor(getColorWithAlpha(Color.BLUE, 0.2f));
    }


    private int getColorWithAlpha(int color, float ratio) {
        int newColor = 0;
        int alpha = Math.round(Color.alpha(color) * ratio);
        int r = Color.red(color);
        int g = Color.green(color);
        int b = Color.blue(color);
        newColor = Color.argb(alpha, r, g, b);
        return newColor;
    }
}

Versión Kotlin:

private fun getColorWithAlpha(color: Int, ratio: Float): Int {
  return Color.argb(Math.round(Color.alpha(color) * ratio), Color.red(color), Color.green(color), Color.blue(color))
}

Hecho

 24
Author: Hiren Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-19 08:51:37

Existe un valor XML alpha que toma valores dobles.

Ya que API 11+ el rango es de 0f a 1f (inclusive) 0f siendo transparente y 1f siendo opaco:

  • android:alpha="0.0" eso es invisible

  • android:alpha="0.5" ver a través

  • android:alpha="1.0" completo visible

Así es como funciona.

 16
Author: eldivino87,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-27 16:26:40

Todo el valor hexadecimal de 100% a 0% alfa, puede establecer cualquier color con los valores alfa mencionados a continuación. por ejemplo, #FAFFFFFF (ARRGGBB)

100% — FF
99% — FC
98% — FA
97% — F7
96% — F5
95% — F2
94% — F0
93% — ED
92% — EB
91% — E8
90% — E6
89% — E3
88% — E0
87% — DE
86% — DB
85% — D9
84% — D6
83% — D4
82% — D1
81% — CF
80% — CC
79% — C9
78% — C7
77% — C4
76% — C2
75% — BF
74% — BD
73% — BA
72% — B8
71% — B5
70% — B3
69% — B0
68% — AD
67% — AB
66% — A8
65% — A6
64% — A3
63% — A1
62% — 9E
61% — 9C
60% — 99
59% — 96
58% — 94
57% — 91
56% — 8F
55% — 8C
54% — 8A
53% — 87
52% — 85
51% — 82
50% — 80
49% — 7D
48% — 7A
47% — 78
46% — 75
45% — 73
44% — 70
43% — 6E
42% — 6B
41% — 69
40% — 66
39% — 63
38% — 61
37% — 5E
36% — 5C
35% — 59
34% — 57
33% — 54
32% — 52
31% — 4F
30% — 4D
29% — 4A
28% — 47
27% — 45
26% — 42
25% — 40
24% — 3D
23% — 3B
22% — 38
21% — 36
20% — 33
19% — 30
18% — 2E
17% — 2B
16% — 29
15% — 26
14% — 24
13% — 21
12% — 1F
11% — 1C
10% — 1A
9% — 17
8% — 14
7% — 12
6% — 0F
5% — 0D
4% — 0A
3% — 08
2% — 05
1% — 03
0% — 00
 12
Author: Anant Shah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-14 09:57:55
<TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:alpha="0.9"
        />

Alfa oscila entre 0 (transparente) y 1(opaco) en Android API 11+

 5
Author: Naramsim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-19 10:01:26

Podemos hacer transparente de esta manera también.

Código de color blanco-FFFFFF

70% blanco - #B3FFFFFF.

100% - FF 95% - F2 90% - E6 85% - D9 80% - CC 75% - BF 70% - B3 65% - A6 60% - 99 55% - 8C 50% - 80 45% - 73 40% - 66 35% - 59 30% - 4D 25% - 40 20% - 33 15% - 26 10% - 1A 5% - 0D 0% - 00

 2
Author: Ashish Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-05 04:21:02

Ver Popularidad debajo de TextView usando esto

     android:alpha="0.38"

introduzca la descripción de la imagen aquí

XML

android:color="#3983BE00"    // Partially transparent sky blue

Dinámicamente

Btn.getBackground().setAlpha (128); / / 50% transparente

Tv_name.getBackground().setAlpha (128); / / 50% transparente

Where the INT ranges from 0 (fully transparent) to 255 (fully opaque).


  <TextView
            style="@style/TextAppearance.AppCompat.Caption"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:alpha="0.38"
            android:gravity="start"
            android:textStyle="bold"
            tools:text="1994|EN" />

Android: alfa="0.38"

Text View alpha property set 0.38 to your textView visibility is faid 
 1
Author: Keshav Gera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-25 07:01:46

Aquí hay una solución programática de la respuesta de @Aromero para calcular el valor hexadecimal para el canal alfa. :)

 public static void main(String[] args) throws Exception {
    final Scanner scanner = new Scanner(System.in);
    int transPerc;
    float fPerc;
    System.out.println("Enter the transparency percentage without % symbol:");
    while((transPerc=scanner.nextInt())>=0 && transPerc <=100){
        fPerc = (float) transPerc / 100;
        transPerc = Math.round(255 * fPerc);
        System.out.println("= " + Integer.toHexString(transPerc));
        System.out.print("another one please : ");
    }
    scanner.close();
}
 0
Author: theapache64,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:32

Pruebe este código :)

Es un código hexadecimal totalmente transparente- "#00000000"

 0
Author: Agilanbu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-11 05:16:52