Cardview android shadow color

Take control of view’s shadow — Android

You can find updated code that is written in Kotlin here

Apr 23, 2017 · 4 min read

Let’s say you’re looking for how to implement shadow on your View in Android and you are going to Google something. You will probably find these 3 answers.

We are going to check these answers, and after we check them all I will suggest new way that you can implement shadow in any View you want.

Use drawable with multi different color solid (worse thing that you can do)

Just use 5–6 shapes that have padding, and at the end the shape that will be your view’s main background, those shapes will be overlapping on each other and Baam! you have drop shadow

Let’s see t he result. Yes for some people this one is acceptable (not for me), but let’s enable Debug GPU Overdraw and check result too

4x+ Overdraw it’s not good, so never ever ever ever use this solution, not worth it.

Android elevation (supported from API 21)

It’s easy to use, just add one attribute to your view’s XML or even enable it with Java code in your View class check Android documentation

The result is perfect, overdraw is acceptable but you older APIs will not support this shadow

Let’s check overdraw and the result.

Do you see that green border on left|top|right of overdraw result that means some part of view overdraw 2x time I have no idea why this is happening.

CardView

When you are using CardView you will see shadow in all APIs, but the result in older APIs are not same as 21+ APIs

Cardview overdraw is exactly same as elevation

But there is one thing you should know; if you go to CardView source code you will notice that CardView extends from FrameLayout (link), That means if you want to use LinearLayout as Parent View it will add inside of Framelayout, so you will always have one more extra overdraw in your views. And when you are using CardView (Elevation) you can not change the shadow’s color, you can not change the shadow’s direction (top|left, bottom|right) you need to follow material design in your application.

Читайте также:  Как дольше сохранить заряд батареи андроид

Using Shape Drawable (New way to implement shadow)

Why not create the shadow ourself? You need to create a custom view and initial in background.

First, let’s see the result.

The result is same as CardView, we don’t have that green 2x overdraw and you can use it in any view you want and you can control your shadow’s direction and color.

Here is just a simple example how it works.

You can add this view in your XML and you have LinearLayout that support rounded box with drop shadow.

You can create your own attribute and pass background color, corner radius, shadow color through XML too.

And the good part is you are not forced to use FrameLayout as your parent view, you can easily create any view you want.

Let’s go to ViewUtils class and see magical things.

This function generate shadow with 3 different direction with custom radius and color.

First, we create background paint to draw our background color and we will add shadow layer with only corner radius that we want.

Next, we add padding to shape drawable to prevent overlapping view’s content on the shadow layer.

With ‘setShadowLayer’ you can change the color of shadow and also the direction of shadow and after that, you need to add a corner to your shadow layer too.

And at the end we merge it to LayerDrawable and set Inset to drawable for not seeing cutting shadow, that’s all.

It’s just simple example,you can use more that one ShapeDrawable to create customizable shadow.

In the next post, I will show how you can clip shape in view with shadow background.

Источник

Cardview android 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

Источник

Using the CardView

Android 7.0 introduces a new widget called CardView which essentially can be thought of as a FrameLayout with rounded corners and shadow based on its elevation. Note that a CardView wraps a layout and will often be the container used in a layout for each item within a ListView or RecyclerView.

CardView should be used when displaying heterogeneous content (where different cards show different types of information). Using a list or a grid of tiles (non-cards) for homogeneous content is preferred since the boundaries in a card can distract the user from quickly scanning a list.

Lets assume your layout looks something like this:

To create a card using this layout, first you need to import the CardView from AndroidX library in your build.gradle file.

Now replace the FrameLayout with CardView .

CardView provides a default elevation and corner radius so that cards have a consistent appearance across the platforms. However, you may choose to customize these values if you desire to do so. We can also set the background color of the card.

Note that the card_view:cardElevation is used to determine the size and softness of the shadow so as to realistically depict the depth. These properties can be set programmatically as well:

See the CardView docs for additional properties.

By default, a CardView is not tappable and it doesn’t show any touch feedback. Touch feedback animations provide users with visual feedback when a CardView is touched. To enable this behavior, add the following attributes to your CardView .

Using the android:foreground=»?android:attr/selectableItemBackground» property on a CardView enables the ripple effect to originate from the touch origin.

On platforms before Android L, CardView adds padding to support corner radius, since rounded corner clipping can be an expensive operation. Similarly, for shadows, before L, CardView adds content padding and draws shadows to that area. This content padding is based on the elevation, and as per the docs:

This padding amount is equal to maxCardElevation + (1 — cos45) * cornerRadius on the sides and maxCardElevation * 1.5 + (1 — cos45) * cornerRadius on top and bottom.

Thus, if you would like to specify custom padding on the content, you need to use a new attribute card_view:contentPadding .

Similarly, to change the background color of a CardView, you need to use a new attribute card_view:cardBackgroundColor .

Источник

Cardview android 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

Источник

Урок 4. Android Material Design. Установка теней и обрезка View

Перевод документации официального сайта developer.android.com

Рисунок 1. Тени для различных высот view.

Чтобы установить высоту view в макете используйте атрибут android:elevation. Чтобы установить высоту в коде activity, используйте метод View.setElevation().

Чтобы установить смещение, используйте метод View.setTranslationZ().

Новые методы ViewPropertyAnimator.z() и ViewPropertyAnimator.translationZ() позволяют легко анимировать высоту view. Для получения дополнительной информации, смотрите справку по ViewPropertyAnimator и руководство разработчика о свойствах анимации.

Вы так же можете использовать StateListAnimator чтобы установить анимации декларативно. Это особенно полезно в тех случаях, когда изменяется состояние триггера анимации, например, когда пользователь нажимает на кнопку. Для получения дополнительной информации, смотрите Изменение состояния анимации view.

Значение Z измеряется в dp (density-independent pixels).

Настройте тени и контуры

Границы фона drawable view определяют форму его тени. Контуры представляют собой внешнюю форму графического объекта и определяют область для сенсорного отклика.

Рассмотрим view, определенное с помощью фона dravable:

Фон drawable определен как прямоугольник с закругленными углами:

View отбрасывает тень с закругленными углами, после того как фон drawable установил границы view. Создание пользовательского контура переопределяет форму тени view по умолчанию.

Чтобы установить пользовательский контур для view в коде:

1. Унаследуйтесь от класса ViewOutlineProvider.
2. Переопределите метод getOutline().
3. Назначьте нового поставщика контура для вашего view с помощью метода View.setOutlineProvider() .

Вы можете создать овальные и прямоугольные очертания с закругленными углами используя методы класса Outlines. Поставщик контура для view по умолчанию получает контур из фона view. Чтобы view не отбрасывала тень, установите значение поставщика контура в null.

Обрежьте view

Обрезание позволяет вам легко изменить форму view. Вы можете обрезать view для совместимости с другими элементами дизайна или изменить форму view в ответ на действия пользователя. Вы можете обрезать view к его области контура с помощью метода View.setClipToOutline() или используя атрибут android:clipToOutline. Только прямоугольник, круг и скругленный прямоугольник поддерживают обрезание, как определено в методе Outline.canClip().

Чтобы обрезать view в форме drawable, установите drawable в качестве фона view (как показано выше), и вызовите метод View.setClipToOutline().

Обрезание view это дорогостоящая операция, поэтому не анимируйте форму, которую вы используете чтобы обрезать view. Для достижения этого эффекта используйте Reveal эффект анимации.

Источник

Читайте также:  Автомагнитола junsun 2 din android
Оцените статью