- Mastering Shadows in Android
- What is 3D?
- What is Depth in Android?
- What is Z-value in Android?
- Add shadow to button android
- Adding Button to Layout
- Button Attributes
- Enabling and disabling Button
- Button Drawable
- Android Image Button
- Xml drawable selector example
- Handling Button Clicks
- Android Button Design and Styles
- Button Styles Customization
- Rounded Corner Button
- Button Elevation and Shadow
- Button Shadow Animation Customization
- About
- Как создать тень для кнопки
- arvkmr / Round_white_button_drop_shadow.xml
- Делаем красивые кнопки в Android
- Добавляем кнопку на разметку
- Атрибуты кнопки
- Включение и выключение кнопки
- Кнопка с Drawable
- ImageButton
- Обработка нажатий на кнопку
- Дизайн и стили кнопок
- Настройка стилей кнопок
- Кнопка с закруглёнными углами
- Высота и тень кнопки
- Настройка анимации тени
- Простая кнопка логина
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.
Источник
Add shadow to button android
September 06, 2017
One of the important UI components in applications is Button. Button can be used to provide actions for user to perform and attach user events to back end behavior.
This post gives details about using and styling android button with examples.
Adding Button to Layout
Android user interface is defined in layout xml file. You can add Button element and set attributes to xml manually. Or using android studio layout design tool, you can add button component from palette to layout and set attributes.
Button Attributes
Button is a subclass of TextView and inherits attributes from TextView and View classes. Below are some of the important button attributes which can be used to defined desired button look and behavior.
- background : to set background to either color or a drwable.
- onClick : to set method that needs to be run when a button is clicked.
- minHeight : to define minimum height of button
- minWidth : to define minimum width of button.
- stateListAnimator : to define animation when button state changes.
- focusable : to indicate whether keystroke should work
- clickable : to indicate whether button is clickable or not
- gravity : to set button text alignment.
- textAppearance : to set text style.
Enabling and disabling Button
You can use enabled attribute to enable and disable button by setting it to true or false. A button can be enabled or disabled in program by calling setEnabled method as shown below.
Button Drawable
You can make button display image and text using drawableTop, drawableBottom, drawableRight, and drawableLeft attributes below screen shot shows output of setting them.
Android Image Button
Android provides ImageButton which can be used to make an image as button. To set an image, you can use src attribute of ImageButton. You can even use different images to be shown in different button states by defining xml drawable selector as shown below.
Xml drawable selector example
Handling Button Clicks
Button clicks can be handled in two ways. First one is by setting onClick attribute of Button in layout xml. Second one is by assigning on click listener to button in activity or fragment.
To set onClick attribute, first define a public void method with View as argument in activity or fragment and use the method name as value to set onClick attribute as shown below.
Below code shows handling button clicks using on click listener.
Android Button Design and Styles
You can apply styles and themes to change look and feel of buttons. Android platform provides pre-defined material styles. Read material styles and compatibility post to learn about android material styles. Below screen shot shows buttons styled with different material styles.
Applying theme or style to button.
Button Styles Customization
You can change the default colors of material styles applied to button by setting colorAccent attribute at application level and colorButtonNormal attribute at widget level to the desired colors. Attribute colorControlHighlight is used to set color for button when it is in pressed state.
Once you define custom style, you can apply it to buttons using theme attribute. Below is an example of custom theme.
Rounded Corner Button
You can define inset as shown below to create rounded corner button and save the drwable xml in res/drawable folder. You can increase or decrease corners element’s radius attribute to adjust button corner radius.
Then define style setting the background attribute to the xml drawable and apply it to button using style attribute.
Button Elevation and Shadow
You can set elevation and translationZ attributes to draw shadow of button.
Button Shadow Animation Customization
You can define different shadow properties for different states of button and animate the transition by defining selector. You can apply the animator to button using stateListAnimator property.
Notice that stateListAnimator set to null in the above (elevation and translationZ) example. This was done to remove default animator applied using stateListAnimator attribute in material themes for button. In order for elevation and translationZ to work, stateListAnimator needs to be set to null.
To customize the animation, meaning animating shadow transition between button states, you need to define selector as shown below in res/animator folder and set stateListAnimator property of custom theme to the defined animator.
Below is an example of state animator.
Apply the below custom theme, which is using state animator, to a button using style or theme attribute.
About
Android app development tutorials and web app development tutorials with programming examples and code samples.
Источник
Как создать тень для кнопки
Как вы можете видеть на картинке, я хочу, чтобы тень за Button . Я создал Button с закругленными углами. Но проблема в том, что я не могу создать тень за этой Button . Как я могу это достичь?
Используйте этот подход, чтобы получить желаемый вид.
Button_selector.xml:
И в вашем XML-макете:
Для Android версии 5.0 и выше
Попробуйте Elevation для других видов.
Ниже версии 5.0,
Для всех просмотров,
Если вы нацеливаете устройства до Lollipop, вы можете использовать Shadow-Layout , так как это легко, и вы можете использовать его в разных типах макетов.
Добавьте теневой макет в файл Gradle :
В верхней части xml-макета, где у вас есть кнопка, добавьте вверху :
Он предоставит пользовательские атрибуты.
Затем вы помещаете вокруг себя макет тени. Button :
Затем вы можете настроить параметры app: в соответствии с вашей теневой тенью.
Здесь моя кнопка с тэгом «cw_button_shadow.xml» под возможностью рисования
Моя кнопка xml, размер вашей высоты и веса
Я пробовал код сверху и сделал свою собственную тень, которая немного ближе к тому, чего я пытаюсь достичь. Может быть, это тоже поможет другим.
Источник
arvkmr / Round_white_button_drop_shadow.xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
xml version = » 1.0 » encoding = » utf-8 » ?> |
selector xmlns : android = » http://schemas.android.com/apk/res/android » > |
item > |
layer-list > |
item > |
shape android : shape = » oval » > |
gradient |
android : startColor = » #FF000000 « |
android : endColor = » #00000000 « |
android : gradientRadius = » 31dp « |
android : type = » radial « |
/> |
shape > |
item > |
item android : top = » 4dp » android : left = » 4dp » android : right = » 4dp » android : bottom = » 4dp » > |
shape android : shape = » oval » > |
size android : width = » 55dp « |
android : height = » 55dp »/> |
solid android : color = » @android:color/white »/> |
shape > |
item > |
layer-list > |
item > |
selector > |
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
Делаем красивые кнопки в Android
Одним из важных компонентов пользовательского интерфейса в приложения является кнопка. Она используется для выполнения различных действий пользователя.
В этой статье мы приведём примеры использования и стилизации кнопки.
Добавляем кнопку на разметку
Пользовательский интерфейс приложения определён в XML-файле с разметкой. Вы можете добавить элемент Button и установить атрибуты вручную. Или вы можете, воспользовавшись инструментом дизайна, добавить Button из палитры элементов и задать атрибуты.
Атрибуты кнопки
Button является подклассом TextView и наследует атрибуты от TextView и View. Ниже приведены некоторые важные атрибуты кнопки, которые можно использовать для настройки стиля и поведения.
- background: установка в качестве фона как цвета, так и drawable
- onClick: установить метод, который будет запускаться при нажатии на кнопку
- minHeight: для определения минимальной высоты кнопки
- minWidth: для определения минимальной ширины кнопки
- stateListAnimator: определение анимации при изменении состояния кнопки
- focusable: для определения того, будет ли обработано нажатие клавиши
- clickable: указать, является ли кнопка кликабельной
- gravity: установка выравнивания текста кнопки
- textAppearance: установить стиль текста
Включение и выключение кнопки
Вы можете использовать атрибут enabled для включения или выключения кнопки, установив его в true или false. Также это можно сделать программно, вызвав метод setEnabled(), как показано ниже:
Кнопка с Drawable
Вы можете отображать на кнопке вместе с текстом изображение, используя drawableTop, drawableRight, drawableBottom или drawableLeft, в зависимости от того, где располагать картинку, как показано на скриншоте ниже.
ImageButton
Android также предоставляет ImageButton, задачей которого является использование изображения в качестве кнопки. Чтобы установить изображение, вы можете использовать атрибут src. Вы также можете использовать разные изображения, которые будут меняться в зависимости от состояния кнопки, меняя в XML drawable selector как показано ниже.
Пример XML drawable selector
Обработка нажатий на кнопку
Клики можно обрабатывать двумя способами. Первый — это установить атрибут onClick в разметке XML. Второй — назначить кнопке слушатель в коде активности или фрагмента.
Чтобы установить атрибут onClick, сначала определите метод типа void, принимающий в качестве параметра View, в активности или фрагменте и затем используйте имя этого метода как значение для атрибута onClick, как показано ниже.
Ниже приведён код обработки нажатия с помощью слушателя.
Дизайн и стили кнопок
Вы можете применять стили и темы для изменения внешнего вида кнопок. Платформа Android предоставляет заранее определённые стили. На рисунке ниже вы можете увидеть, как отображаются кнопки с различными стилями.
Пример применения темы для кнопки.
Настройка стилей кнопок
Вы можете изменить цвета по умолчанию для стилей, применяемых к кнопке, установив атрибут colorAccent на уровне приложения и атрибут colorButtonNormal на уровне виджета для нужных цветов. Атрибут colorControlHighlight используется для установки цвета кнопки, когда она находится в нажатом состоянии.
Как только вы определите собственный стиль, вы можете применить его к кнопкам с помощью атрибута theme. Ниже приведен пример пользовательской темы.
Кнопка с закруглёнными углами
Вы можете определить элемент inset, как показано ниже, чтобы создать кнопку с закруглёнными углами и сохранить файл с drawable в папке res/drawable. Вы можете увеличить или уменьшить атрибут радиуса элемента, чтобы отрегулировать радиус углов кнопки.
Затем определите стиль, задающий атрибут background для xml drawable и примените его к кнопке с помощью атрибута style.
Высота и тень кнопки
Вы можете установить атрибуты elevation и translationZ, чтобы нарисовать тень кнопки.
Настройка анимации тени
Вы можете определить различные свойства теней для разных состояний кнопки и анимировать переход путём определения селектора. Вы можете применить аниматор к кнопке, используя свойство stateListAnimator.
Обратите внимание, что stateListAnimator установлен в null в приведённом выше примере. Это было сделано для удаления аниматора по умолчанию, чтобы elevation и translationZ работали.
Чтобы настроить анимацию тени при изменении состояния кнопок, вам нужно определить селектор, как показано ниже, в папке res/animator и установить свойство stateListAnimator своей темы для определённого аниматора.
Примените следующую тему, которая использует аниматор, к кнопке с использованием атрибута style или theme.
Простая кнопка логина
Совмещая всё вышесказанное, можно создать красивую кнопку, позволяющую, например, заходить пользователям на свои аккаунты. Код разметки будет выглядеть следующим образом:
Кроме того, с помощью атрибута drawableLeft можно добавить изображение к нашей кнопке, в том числе и векторное. На старых устройствах, векторные изображения вызывают падение всего приложения, поэтому сделаем это программно в коде активности при помощи AppCompatResources:
Метод setCompoundDrawablesWithIntrinsicBounds() делает то же, что и атрибуты drawableLeft, drawableTop и так далее. В качестве параметров нужно указать, где именно будет размещаться изображение (указываем null в случае, если здесь изображение не нужно).
Источник