Mastering Shadows in Android
Jan 9, 2018 · 6 min read
If we want to create better apps, I believe that we need to follow material design guideline.In general terms, Material design is a three-dimensional environment containing light, material, and cast shadows. Light and Shadow are important for us if we want to follow material design guideline in our application development process.
I will try to explain following topics in this article.
- 3D in Android
- Depth
- Z value, elevation and Translation Z
- Light
- Button state (Pressed and Resting)
- Outline
- Custom Outline with ViewOutlineProvider
Before deep dive into shadow and light, I want to show you what our environment is.
What is 3D?
The material environmen t is a 3D space, which means all objects have x, y, and z dimensions. The z-axis is perpendicularly aligned to the plane of the display, with the positive z-axis extending towards the viewer. In Material Design world, every object has 1 dp thickness.
What is Depth in Android?
Material design differs from other design guides because It has depth. We can say that depth defines view’s importance level in user interface. We can think there is a paper layer in our desk. If we put another paper on it, our eyes will perceive that it has a depth.
Let’s imagine it with an app screenshot from the material design guideline.
Let’s see our elements in the screen.
- Screen (Surface layer — 0 depth)
- Cardviews
- Appbar Layout
- Floating Action Button
Every element has a priority to another. Cardviews can scroll in its recyclerview. So we can say that our first layer is scrollable content. The second layer is appbar layout. The third layer (Top layer) is the floating action button.
So how do we define the order? How do we make the user feel the depth? Answer: Z- value.
What is Z-value in Android?
The Z value for a view has two components:
- Elevation: The static component.
- Translation Z: The dynamic component used for animations.
I always wonder that what is the difference between elevation and translation.
Elevation is static. So you don’t change it dynamically. If you want to animate your view in Z-axis (like pressing and resting) you need to use translation-Z attribute.
Translation Z is dynamic. In your empty project, If you create a button and press it, you will see that shadow gets bigger with an animation. Actually, elevation value is not changing. Translation Z property is changing. Android is using default state list animator changes translation Z property of the view.
Z-Value = Elevation + TranslationZ
What if we change the value of Z of two views that intersect. Does Android handle the order on the screen? Yes. Let me show you that with a diagram that I designed.
Источник
Android change shadow color
This library draw android view shadow by ShadowLayer. You may don’t like the CardView’s black shadow which we can’t change it’s color. Same to CardView wrap content and set shadow radius. You can change shadow color, foreground color and corner radius everywhere. Because the shadow is draw in the view. So you must add space to draw the shadow. The ShadowView add one param shadowMargin which must be set before you add shadow radius to the view.
Caveat: Margin In UI
= layout_margin + shadow_margin(Add by ShadowView)
H | H | H |
---|---|---|
Change Radius | Change foreground | Change Corners |
Change shadow color | Change shadow margin | Demo |
About
Deprecated because of the performance not fine. Android custom shadow view, can replace your CardView
Источник
Android change shadow color
This library draw android view shadow by ShadowLayer. You may don’t like the CardView’s black shadow which we can’t change it’s color. Same to CardView wrap content and set shadow radius. You can change shadow color, foreground color and corner radius everywhere. Because the shadow is draw in the view. So you must add space to draw the shadow. The ShadowView add one param shadowMargin which must be set before you add shadow radius to the view.
Caveat: Margin In UI
= layout_margin + shadow_margin(Add by ShadowView)
H | H | H |
---|---|---|
Change Radius | Change foreground | Change Corners |
Change shadow color | Change shadow margin | Demo |
About
Android custom shadow view, can replace your CardView
Источник
Android change shadow color
This library draw android view shadow by ShadowLayer. You may don’t like the CardView’s black shadow which we can’t change it’s color. Same to CardView wrap content and set shadow radius. You can change shadow color, foreground color and corner radius everywhere. Because the shadow is draw in the view. So you must add space to draw the shadow. The ShadowView add one param shadowMargin which must be set before you add shadow radius to the view.
Caveat: Margin In UI
= layout_margin + shadow_margin(Add by ShadowView)
H | H | H |
---|---|---|
Change Radius | Change foreground | Change Corners |
Change shadow color | Change shadow margin | Demo |
About
Deprecated because of the performance not fine. Android custom shadow view, can replace your CardView
Источник
Как показать тень вокруг linearlayout в android?
Как я могу показать тень для моего линейного макета. Я хочу белый цвет округлый фон с тенью вокруг linearlayout. Я делал это до сих пор. Пожалуйста, помогите мне. Спасибо заранее.
и rounded_rect_shape.xml в каталоге xml
13 ответов
в Android нет такого атрибута, чтобы показать тень. Но возможные способы сделать это:
добавьте простой LinearLayout с серым цветом, над которым добавьте свой фактический макет, с полем внизу и справа, равным 1 или 2 dp
есть 9-патч изображение с тенью и установить его в качестве фона для вашего линейного макета
существует также другое решение проблемы путем реализации списка слоев, который будет выступать в качестве фона для LinearLayoout.
добавить background_with_shadow.xml-файл в res/drawable . Содержащий:
затем добавьте список слоев в качестве фона в LinearLayout.
Ну, это легко достичь .
просто построить GradientDrawable это происходит от Черного и переходит к прозрачному цвету, чем использовать родительские отношения, чтобы поместить вашу форму близко к представлению, которое вы хотите иметь тень, тогда вам просто нужно дать любые значения высоте или ширине .
вот пример, этот файл должен быть создан внутри res/drawable , Я называю это как shadow.xml :
поместите следующий код выше из LinearLayout , например, установите android:layout_width и android:layout_height to fill_parent и 2.3dp , вы будете иметь хороший эффект тени на LinearLayout .
Примечание 1: если вы увеличиваете android:layout_height будет показано больше тени .
примечание 2: использовать android:layout_above=»@+id/id_from_your_LinearLayout» атрибут если вы размещаете этот код внутри RelativeLayout, в противном случае игнорируйте его.
надеюсь, это поможет кто-то.
для леденца и выше вы можете использовать высота.
для более старых версий:
(toast_frame не работает на KitKat, тень была удалена из тостов)
Источник