Делаем красивые кнопки в 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 в случае, если здесь изображение не нужно).
Делаем красивые кнопки в Android : 1 комментарий
Вообще не понятно откуда брать/как создавать
btn_rounded_corner
element_background
@animator/button_elevation
How to Android button rounded corners | Radius, ripple, corners, design?
Do you want to make the corners of a button round in Android? In this tutorial, you will learn an easy way to achieve this in Android.

To create an Android button rounded corners have to use a new XML file. This new XML file will be inside a drawable folder. To change the corners of all sides of the button need only one attribute in the drawable XML file.
To change one or two or three corners, you have to use the following attributes:-
Step 7. Now Run the application, in an emulator or on your Android device
Output screenshot Android corner button example:

Download source code of button design from an Activity in Kotlin
Q: What is an android material button and how to set the corners (radius) of it?
Answer: Material Button is a customizable button component with updated visual styles
How to Use
Q: How to create a circle button in android?
Answer: Same as the above example, use XML drawable file:
Save the following contents as round_button.xml in drawable folder.
Android Material Effect: Although FloatingActionButton is a better option, If you want to do it using XML selector, create a folder drawable-v21 in res and save another round_button.xml there with the following XML.
And set it as background of Button in xml like this:
Important:
- To show all state: -enabled, disabled, highlighted, etc, you have to use selector as described here.
- You’ve to keep both files in order to make the drawable backward-compatible. Otherwise, you’ll face weird exceptions in the previous android version
Source: https://stackoverflow.com/questions/9884202/custom-circle-button
Q: How to create Android button rounded corners programmatically?
Answer: Here code for how to create GradientDrawable shape programmatically.
And change the radius for all corners of the button.
or Change the radius for specific corners of the button.
And finally, use this drawable as a background as of button widget:
Note: A button design topic is UI design. in this tutorial, we used a Kotlin programming language in Main Activity and will work the same with java code.
Do comment if you have any doubts and suggestions on this tutorial.
Note: This example (Project) is developed in Android Studio 3.3.2. Tested on Android 9 ( Android-P), compile SDK version API 28: Android 9.0 (Pie)
MinSdkVersion=”25″
TargetSdkVersion=”28″
Coding in Kotlin
Как закруглить кнопку в android studio
![]()
There is no default attribution to make a button round in Android Studio. So to do that we have to add a new XML file to make the button round.
Drawable > New > Drawable Resource File (example: rounded_corner.xml)
Color and corner radius for the button can be modified as per your needs. The changes you make can be seen in the design option in the side:
Now , in the main xml file where you want the rounded corners for the button , add this line : android:background=”@drawable/rounded_corner ” .
Android Button Design, Custom Button, Round Button, Color

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
In this tutorial, we’ll be customizing the Buttons in our Android Application. If you aren’t aware of Android Buttons, check out this tutorial before proceeding. We’ll be setting selectors and shapes on our buttons in xml.
Android Button Design
A selector is used to define a different behaviour for different states of the Button. What are drawable states? Each of the following events of a view (Button or any other kind of view) are a type of state:
- state_pressed
- state_selected
- state_focused
- state_enabled
state_focused is when you hover over the widget. Typically works only on emulators. state_selected is meant to select the view. Doesn’t work with Buttons. Works with RadioButtons. Typically for a button, there are just three important states: normal, pressed and enabled. For each of the states of the selector, we can set a different drawable/color/shape on our button. Let’s get started with the implementation of each of these in a new Android Studio Project.
Android Custom Button Project Structure
We’ll be looking at each of the drawable files one at a time. The colors are defined in the colors.xml file : A selector can be an xml file created inside the drawable folder. Selector for different background colors. The following selector file btn_bg_selector.xml contains the code for setting different background colors on a button for different states.
In the above code, each of the states is represented using item tag. The selector tag behaves like an if — else if statement to an extent. It checks every condition from top to bottom. Whenever the condition matches, it sets the relevant things on the button and stops processing the next item tags. The third item tag is the default one. It’s important that we keep it at the last. Keeping it at the top would not allow the other two item tags to get executed ever. We set the above drawable selector file on our button in the activity_main.xml as:
The selector is set on the background attribute of the button.
Selector for Disabled Button
The following selector btn_bg_selector_disabled.xml is used on a button which is not enabled.
For the above selector to work, we need to specify android:enabled as false.
Selector with Different Drawables
We can set a different drawable image to be displayed based upon the state of the button. The selector code that does so is present in the file btn_drawable_selector.xml
Note: The focused state doesn’t work on smart phones. Now the drawable images when set as the button background can get stretched if it’s width/height is larger than the button’s. So we need to set the Button width/height in accordance with the drawable image. We can do so either by hardcoding in xml or getting the drawable dimensions programmatically and setting it over the button. For the sake of convenience we’ve done the former here:
ImageButton is the ideal View to be used when you need to display a drawable as the button background only since it fits the drawable appropriately. ImageButton comes with the android:scale attribute to resize the drawable image.
Android Button Color
We can change the text color on the button based on the state in the selector. The following code from btn_txt_selector.xml does so. We need to use android:color here in place of android:drawable .
The button in the layout:
Android Button Shapes
We can set custom shapes on our button using the xml tag <shape> . These xml files are created in the drawable folder too. shape can be used inside selectors . The shape can be set to rectangle (default), oval , ring , line . The most used tags inside the shape tag are:
- <gradient> — Setting start and end colors of the gradient along with the type(radius, linear, sweep)
- <stroke> — Setting border color and width
- <solid> — Setting the solid color on the button
- <corners>— Setting radius
Android Round Corner Button
The xml code for the btn_shape_round.xml file is given below:
Just like selectors, we can set this on the android:background tag on the Button in our xml layout.
Android Button Shape With Gradient
In the following btn_shape_gradient.xml file, we’ve set the gradient as a radial one. We must set the gradient_radius attribute too.
Android Button Shape and Selector Together
The btn_selector_shape.xml holds the selector. Each of the items has a shape specified.
Set this on the Button and the shape would change from rectangle to oval when the button is clicked. A linear gradient should have the angle specified in the multiples of 45, else it’ll crash. Setting the Button shape as capsule btn_shape_capsule.xml is where we set the shape inside the selectors as a capsule.
The code for the MainActivity.java class which hosts all of the above button examples is given below.
Android Custom Button Design App Output
The output of the above application in action is given below. This brings an end to this tutorial on Button selectors and shapes. You can download the final android studio project from the below link.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Делаем красивые кнопки в 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 в случае, если здесь изображение не нужно).
Делаем красивые кнопки в Android : 1 комментарий
Вообще не понятно откуда брать/как создавать
btn_rounded_corner
element_background
@animator/button_elevation
Creating Rounded Corner Button In Android Studio
Creating a rounded button in android studio is not so hard. In this android studio tutorial we will learn how to create rounded buttons with different styles. We also create the icon button which can be on the left or right side of the button.
Rounded buttons in android are mostly used because these look good and match with the design of the screen and the theme color. Most of the app screens use round corners buttons.
button in android studio
Button In Android Studio
Buttons in android studio are used to perform some task when we tap or press on it. These are the parts of GUI which have the feature of tapping or clicking. They call any function or move to another screen or can do anything which we want to perform. Rounded Buttons are also the same button in android studio, we provide the radius of the corners of the button so it becomes a rounded button.
By default android studio provides a Button widget which we can use but we can not provide rounded corners of it. We have to create a drawable design to make it rounded corners.
Default Button Of Android Studio
button in android studio
In the above screen there is a simple button we can not round its corners. We can change its background color and other properties. This is the default button in android studio.
Creating Rounded Corner of The Simple Button in android Studio
To create the rounded corner of the default Button provided by the android studio, we have to create a Drawable layout as follows and use as below in the button attribute.
Create a drawable layout inside the Drawable directory. Copy and paste following code you can change the background color and radius.
rect_rounded_button.xml
Now use as below in Button attribute.
rounded button in android studio
How to Change The Background Color of Default Button in Android Studio
Use following code to change the background color of default button in android studio.
button in android
Material Design Button in Android Studio
The other type of button is Material design Button in android. These buttons are designed by the material design library anyone can use this button and its other designs.
You should be happy to read that the material design button has the attribute of round shape that is easy to use. There are many other features which are more that the default button of android studio.
Material Design Dependency
Add the following material design library in your build,gradle file. Higher versions of android studio already have this material design library.
Use MaterialButton widget in your layout file.
Rounded Corners of Material Button
Use following attribute to provide radius of corners.
How to Change the Background Color of Material Design Button
To change the background color of the material design button use the following feature inside the Material Button widget.
Complete code of Material Rounded Button in Android Studio
Use the following code to create the rounded corner button in your android project. You can see more features on the material design website.
material button in android
Click Event On Button
SetOnClickListener() used to create a Tap or Click event. Write setOnclick and you will see dropdowns, select setOnclickListener from there and write new and capital O in parantheses and select the method from dropdown. Use following code for button click event.
Please comment if this tutorial is helpful to you even if there is any issue in this code.
We suggest you to learn android DataBinding in android which is most useful for android developers. DataBinding is easy and simple to learn.
Learn more Android and Flutter tutorials which will improve your development skills.
Android Button Design, Custom Button, Round Button, Color

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
In this tutorial, we’ll be customizing the Buttons in our Android Application. If you aren’t aware of Android Buttons, check out this tutorial before proceeding. We’ll be setting selectors and shapes on our buttons in xml.
Android Button Design
A selector is used to define a different behaviour for different states of the Button. What are drawable states? Each of the following events of a view (Button or any other kind of view) are a type of state:
- state_pressed
- state_selected
- state_focused
- state_enabled
state_focused is when you hover over the widget. Typically works only on emulators. state_selected is meant to select the view. Doesn’t work with Buttons. Works with RadioButtons. Typically for a button, there are just three important states: normal, pressed and enabled. For each of the states of the selector, we can set a different drawable/color/shape on our button. Let’s get started with the implementation of each of these in a new Android Studio Project.
Android Custom Button Project Structure
We’ll be looking at each of the drawable files one at a time. The colors are defined in the colors.xml file : A selector can be an xml file created inside the drawable folder. Selector for different background colors. The following selector file btn_bg_selector.xml contains the code for setting different background colors on a button for different states.
In the above code, each of the states is represented using item tag. The selector tag behaves like an if — else if statement to an extent. It checks every condition from top to bottom. Whenever the condition matches, it sets the relevant things on the button and stops processing the next item tags. The third item tag is the default one. It’s important that we keep it at the last. Keeping it at the top would not allow the other two item tags to get executed ever. We set the above drawable selector file on our button in the activity_main.xml as:
The selector is set on the background attribute of the button.
Selector for Disabled Button
The following selector btn_bg_selector_disabled.xml is used on a button which is not enabled.
For the above selector to work, we need to specify android:enabled as false.
Selector with Different Drawables
We can set a different drawable image to be displayed based upon the state of the button. The selector code that does so is present in the file btn_drawable_selector.xml
Note: The focused state doesn’t work on smart phones. Now the drawable images when set as the button background can get stretched if it’s width/height is larger than the button’s. So we need to set the Button width/height in accordance with the drawable image. We can do so either by hardcoding in xml or getting the drawable dimensions programmatically and setting it over the button. For the sake of convenience we’ve done the former here:
ImageButton is the ideal View to be used when you need to display a drawable as the button background only since it fits the drawable appropriately. ImageButton comes with the android:scale attribute to resize the drawable image.
Android Button Color
We can change the text color on the button based on the state in the selector. The following code from btn_txt_selector.xml does so. We need to use android:color here in place of android:drawable .
The button in the layout:
Android Button Shapes
We can set custom shapes on our button using the xml tag <shape> . These xml files are created in the drawable folder too. shape can be used inside selectors . The shape can be set to rectangle (default), oval , ring , line . The most used tags inside the shape tag are:
- <gradient> — Setting start and end colors of the gradient along with the type(radius, linear, sweep)
- <stroke> — Setting border color and width
- <solid> — Setting the solid color on the button
- <corners>— Setting radius
Android Round Corner Button
The xml code for the btn_shape_round.xml file is given below:
Just like selectors, we can set this on the android:background tag on the Button in our xml layout.
Android Button Shape With Gradient
In the following btn_shape_gradient.xml file, we’ve set the gradient as a radial one. We must set the gradient_radius attribute too.
Android Button Shape and Selector Together
The btn_selector_shape.xml holds the selector. Each of the items has a shape specified.
Set this on the Button and the shape would change from rectangle to oval when the button is clicked. A linear gradient should have the angle specified in the multiples of 45, else it’ll crash. Setting the Button shape as capsule btn_shape_capsule.xml is where we set the shape inside the selectors as a capsule.
The code for the MainActivity.java class which hosts all of the above button examples is given below.
Android Custom Button Design App Output
The output of the above application in action is given below. This brings an end to this tutorial on Button selectors and shapes. You can download the final android studio project from the below link.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.