- Android Dev Tip #3
- Using @android:color/transparent in gradients
- Explanation:
- Example:
- If you enjoyed this post, please show your support! Recommend, follow, comment, share.
- Android Hub 4 you : the free android programming tutorial
- Pages
- Monday, May 19, 2014
- Android Transparent Background | Set Opacity in Android | Make android application with transparent background
- 15 comments:
- Программирование под Android. Задание элементам прозрачных и полупрозрачных оттенков (цветов).
- Как создать прозрачную активность на Android?
- 18 ответов:
- цвета.xml
- есть два способа:
- Как мне создать прозрачную активность на Android?
- colors.xml
Android Dev Tip #3
Using @android:color/transparent in gradients
Jan 25, 2017 · 4 min read
This one is extremely basic and perfectly logical if you spend at most few seconds thinking about it. Nevertheless I have seen so many people struggling with it and I’ve been asked so many times about it, I decided to include it in the Dev Tip series.
If you’re creating a gradient in xml with a part being completely transparent, be really careful when using @android:color/transparent.
Explanation:
When drawing a gradient, Android framework takes two colors representing two edges of the gradient section ( startColor — centerColor or centerColor — endColor or startColor — endColor when no centerColor is specified) and interpolates values between them.
That means that the framework takes all four components of the color value ( Alpha, Red, Green and Blue) and interpolates each and every single one of them for the particular part of gradient.
Here’s an example of creating a gradient between two colors:
if there were only 3 steps (colors) between them.
The values o f the particular color components ( A, R, G and B) at a particular stage of the gradient can be represented as:
When using @android:color/transparent you need to remember that it represents a completely transparent version of a particular color (opacity set to 0%; A component is equal to #00). You cannot forget this color has its own RGB components which are NOT skipped when calculating gradient values.
If you look at the Color class (from the android.graphics ) you can see that Color.TRANSPARENT (which represents the same thing as @android:color/transparent ) is equal to 0 .
The hex representation of 0 is #00000000 , which means that Color.TRANSPARENT is essentially a completely transparent Color.BLACK .
Example:
When creating a simple green-to-transparent gradient you might end up trying to use something like this:
With the visual result being:
Looks kind of ugly, doesn’t it? The gradient transforms #FF27AE60 green ( #FF Alpha channel means 100% opacity) to completely transparent black ( #00000000 ). Take a look at how particular components of the color are changing:
If you think about that for a second, you should realize that creating a simple COLOR-TO-TRANSPARENT gradient shouldn’t modify RGB values at all. It should only affect the Alpha component. Which obviously isn’t the case here.
When using @android:color/transparent we cannot forget that Red, Green and Blue of this color are also taken into consideration when calculating color values for gradient. Not only the Alpha channel.
The proper way to generate this sort of gradient would be to use this:
Use the exact same color but change the opacity ( Alpha) value to #00 . The effect you would achieve is this (as expected):
And components would change in the following way:
R, G and B components are not changing. Only the Alpha channel is affected by the gradient.
If you enjoyed this post, please show your support! Recommend, follow, comment, share.
Источник
Android Hub 4 you : the free android programming tutorial
Pages
Monday, May 19, 2014
Android Transparent Background | Set Opacity in Android | Make android application with transparent background
I am again here with very small and important demo in android. How to make your activity transparent and how to set opacity in background. I am sharing code here step by step-
15 comments:
I was helpful in making my project initial steps.
Thanks
plzzz where to make this tell me
i mean, the line under the screenshot, activity. where that activity to b performed
in what lines can find or put dis codes?
Good demo.
Can you send me the code for displaying a translucent image at a particular position on screen on to the other image in the background??
I want to see both the images, one in full screen in the background and other as translucent image at the particular position on the screen. hope u got my point.
Thanks in advance.
I don’t have any code but you can set that layout parent as transparent using color code- #00000000.
Hello,
good quick demo thanks.
I’m pretty sure I’ve got everything in the right place but i get this error:
java.lang.RuntimeException: Unable to start activity ComponentInfo
All i have done is set the Manifest to have the android:theme=»@android:style/Theme.Translucent» and the activity_main with the «#80000000».
This was a new project .. blank activity. set to 4.1 compatibility. no other changes. If i remove the Translucent all works fine.
I think you are using android studio v7 support library —
Источник
Программирование под Android. Задание элементам прозрачных и полупрозрачных оттенков (цветов).
Прозрачность цвета задается первыми двумя символами.
Ниже я представлю эти 2 символа и их эквивалент в процентах прозрачности цвета.
Применить их можно так (файл colors.xml ):
color name=»transp» > # 00000000 color >
color name=»transp_black» > # 1A000000 color >
прозрачность —>
color name=»green_transp_15″ > # 2600FF00 color > прозрачность —> color name=»blue_transp_15″ > # 260000FF color > resources >
Таким образом цвет можно назначить так.
// На примере кнопки
Button button_1 = (Button) findViewById(R.id. button_2_1 );
button_1.setBackgroundColor(ContextCompat. getColor (Main_Activity. this , R.color. green_transp_15 ));
Button test_tr = (Button)findViewById(R.id. button_6 );
test_tr.setTextColor(ContextCompat. getColor ( Main_Activity . this , R.color. green_transp_15 ));
Для задания прозрачности элементам (кнопкам, изображениям и т.д.) вы можете использовать в своем макете
0.0 полностью прозрачный, 1,0 полностью непрозрачен.
Вы можете, так же назначить прозрачность в коде.
Для этого есть функция (setAlpha())
На примере кнопки:
Button test_tr = (Button)findViewById(R.id. button_6 );
Подписывайтесь на канал, не пропустите новые публикации.
Источник
Как создать прозрачную активность на Android?
Я хочу создать прозрачную деятельность над другой деятельностью.
Как я могу этого достичь?
18 ответов:
добавьте следующий стиль в вашей (Если у вас его нет, создайте его.) Вот полный файл:
(стоимость @color/transparent цвета стоимостью #00000000 который я положил в . Вы также можете использовать @android:color/transparent в более поздних версиях Android.)
затем примените стиль к своей деятельности, например:
с библиотекой» AppCompat » или «библиотекой поддержки дизайна Android» это немного отличается:
объявите свою активность в манифесте следующим образом:
и добавить прозрачный фон в макет.
назначьте полупрозрачную тему для действия, которое вы хотите сделать прозрачным в файле манифеста Android вашего проекта:
Я хотел бы добавить к этому немного, как я новый разработчик Android, а также. Принятый ответ велик, но я действительно столкнулся с некоторыми проблемами. Я не был уверен, как добавить цвет в цвет.XML-файл. Вот как это должно быть сделано:
цвета.xml
в моих оригинальных цветах.xml файл у меня был тег «drawable»:
и поэтому я сделал это для цвета, но я не понял, что ссылка «@color/ » означала поиск тег «цвет» в XML. Я подумал, что должен упомянуть об этом, чтобы помочь кому-то еще.
Я достиг этого на 2.3.3, просто добавив android:theme=»@android:style/Theme.Translucent» в теге activity в манифесте.
Я не знаю о более низких версиях.
в моем случае, я должен установить тему во время выполнения в java на основе некоторых условий. Поэтому я создал одну тему в стиле (похож на другие ответы):
затем в Java я применил его к своей деятельности:
помню один важное замечание здесь: вы должны назвать
на onCreate, ниже setContentView добавьте следующую строку:
просто пусть фоновое изображение активности будет прозрачным. Или добавьте тему в XML-файл:
самый простой способ, который я нашел, это установить тему активности в AndroidManifest в android:theme=»@android:style/Theme.Holo.Dialog» .
затем в методе onCreate действия вызовите getWindow().setBackgroundDrawable(new ColorDrawable(0)); .
для диалогового действия я использую это:
но вам также нужно установить свой основной вид в действии невидимым. В противном случае фон будет невидимым, а все виды в нем будут видны.
Я просто сделал две вещи, и это сделало мою деятельность прозрачной. Они внизу.
в файле манифеста я просто добавил ниже код в тег активность тег.
и я просто установил фон основного макета для этой деятельности как»#80000000«. Как
это прекрасно работает для меня.
назначьте ему полупрозрачную тему
Примечание 1: в папке Drawable создать тест.XML и скопируйте следующий код
/ / Примечание: углы и форма согласно вашему требованию.
/ / примечание 2: создать xml:
есть два способа:
- С Помощью Тема.NoDisplay
- С Помощью Тема.Полупрозрачный.NoTitleBar
используя Theme.NoDisplay по-прежнему будет работать. но только на старых устройствах Android. На Android 6.0 и выше, используя темы.NoDisplay без вызова finish() in onCreate() (or, technically, before onResume()) будет авария приложение. Вот почему рекомендация использовать Theme.Translucent.NoTitleBar , который от этого не страдает ограничение.»
просто добавьте следующую строку в тег activity в файле манифеста, который должен выглядеть прозрачным.
чтобы избежать Android Oreo связанных аварии на деятельности
Источник
Как мне создать прозрачную активность на Android?
Я хочу создать прозрачное действие поверх другого действия.
Как мне этого добиться?
Добавьте следующий стиль в свой res/values/styles.xml файл (если у вас его нет, создайте его). Вот полный файл:
(Значение @color/transparent — это значение цвета, #00000000 которое я поместил в res/values/color.xml файл. Вы также можете использовать его @android:color/transparent в более поздних версиях Android.)
Затем примените стиль к своей деятельности, например:
Это выглядит так:
В файле styles.xml:
Объявите свою деятельность в манифесте следующим образом:
И добавьте прозрачный фон к вашему макету.
Назначьте полупрозрачную тему для действия, которое вы хотите сделать прозрачным, в файле манифеста Android вашего проекта:
Я хотел бы добавить к этому немного, поскольку я также являюсь новым разработчиком Android. Принятый ответ великолепен, но я столкнулся с некоторыми проблемами. Я не был уверен, как добавить цвет в файл colors.xml. Вот как это должно быть сделано:
colors.xml
В моем оригинальном файле colors.xml у меня был тег «drawable»:
И поэтому я сделал это для цвета, но я не понимал, что ссылка «@ color /» означает поиск тега «color» в XML. Я думал, что должен упомянуть об этом, чтобы помочь кому-то еще.
Я добился этого на 2.3.3, просто добавив android:theme=»@android:style/Theme.Translucent» тег активности в манифест.
Я не знаю о более низких версиях .
В моем случае я должен установить тему во время выполнения в Java на основе некоторых условий. Итак, я создал одну тему в стиле (аналогично другим ответам):
Затем в Java я применил это к моей деятельности:
Источник