- Стили
- Строка состояния
- Меню
- Кнопки
- Выбираемый элемент в Android 5.0 (API 21)
- Значок гамбургера в DrawerLayout
- Android Button Design, Custom Button, Round Button, Color
- Android Button Design
- Android Custom Button Project Structure
- Selector for Disabled Button
- Selector with Different Drawables
- Android Button Color
- Android Button Shapes
- Android Round Corner Button
- Android Button Shape With Gradient
- Android Button Shape and Selector Together
- Android Custom Button Design App Output
- How to create customized Buttons in Android with different shapes and colors
- Approach:
- activity_main.xml
Стили
По умолчанию панель навигации с кнопками «Назад», «Домой» и «Недавние программы» имеет чёрный цвет. Переопределяем (API 21+).
Строка состояния
Можно поменять на Android 5 (Lollipop).
Позже (API 21+) можно уже не указывать targetApi.
Делаем строку состояния прозрачной (API 19+).
Меняем цвет строку состояния на белый (API 23+).
Программный способ (API 21++).
val window = window window.statusBarColor = ContextCompat.getColor(this, R.color.teal_200)
Меню
Переопределяем внешний вид стандартного значка меню в виде трёх точек по вертикальной линии.
Читатели сообщили, что код может не работать и дали ссылку на работающий вариант:
You can use this style (or Theme.AppCompat.Light.NoActionBar):
Кнопки
Обычная кнопка по умолчанию использует стиль buttonStyle, который можно не указывать.
На панели Palette можно увидеть кнопку меньшего размера Small Button, который на экране будет выглядеть чуть меньше стандартной кнопки с уменьшенным шрифтом. Разница заключается в стиле buttonStyleSmall.
Также возможны другие стили. Например, кнопка без окантовки (плоская кнопка) — стиль borderlessButtonStyle. Она покажет свои границы в момент нажатия.
Переопределяем через собственные стили и подключаем через android:theme.
Ещё один стиль, попадавший мне в примерах — buttonStyleInset.
Можно применить стиль Material Design:
У кнопки ToggleButton есть свой стиль buttonStyleToggle:
В Material Design буквы в кнопках и метках выводятся в верхнем регистре. Можно отменить это правило, если добавить строку в используемой теме.
Или более тонкая настройка для кнопки.
Выбираемый элемент в Android 5.0 (API 21)
У компонентов в стиле Material Design при нажатии появляется анимация в виде расходящего круга (ripple). Стиль selectableItemBackgroundBorderless применим к различным компонентам: кнопки, рамки и т.д. Применим к ImageView. В первом случае анимация не распространяется за пределы своего компонента. Во втором случае анимация выходит за пределы границ компонента.
Стоит отметить, что существует упрощённый стиль selectableItemBackground, доступный для старых устройств. В этом случае анимация уже не виде круга, а в более простом варианте. Для первой кнопки в виде прямоугольника внутри своего контейнера. Во втором случае анимация также не выходит за границы своего контейнера.
Значок гамбургера в DrawerLayout
Можно поменять цвет значка гамбургера. Откроем файл стилей res/values/styles.xml и добавим:
Элемент spinBars со значением true позволяет использовать анимацию. В противном случае значок будет статичным.
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
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 .
Android Button Shapes
We can set custom shapes on our button using the xml tag . 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:
- — Setting start and end colors of the gradient along with the type(radius, linear, sweep)
- — Setting border color and width
- — Setting the solid color on the button
- — 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.
How to create customized Buttons in Android with different shapes and colors
A Button is a user interface that are used to perform some action when clicked or tapped.
In this article, we will try to change the shape and color of Button to various designs, like:
Approach:
Below are the various steps to created customized Buttons:
Step 1: Start a new Android Studio project
Please refer to this article to see in detail about how to create a new Android Studio project.
Step 2: Add the Button
Since we only need to customize Buttons, we will just add Buttons in our layout. We don’t need any other widget. This can be done either by writing the code in XML or using the Design Tab. Here, we will do so by adding its XML code.
Now since we need to customize the Button as per 3 shapes (as shown above), we will add 3 buttons and add the customization of each separately, lets say the buttons be – oval, rectangle and cylindrical.
activity_main.xml
Initially, all three buttons have default values and will look as per the default look shown above.
Step 3: Customizing the button
In order to customize the button, as shown above, we will be needing few attributes of Button in particular:
- shape: This defines the shape of the widget that is being used. For example: oval, rectangle, etc.
- color This attribute takes the Hexadecimal color code as parameter and sets the color as per the code
- corner::radius: This attribute defines how much curved corners of the button has to be. For example, no curve will lead to rectangle and increasing the curve can result in circle as well.
- stroke: This attribute refers to the thickness of the outline of the button. The more the stroke, the thicker the outline will be.
These attributes can be set for a widget with the help of a Drawable resource file.
- Creating a new drawable resource file: We will be creating a new drawable file which will contain the customizations such as shape, color, and gradient which we want to set on our button. To create a drawable file, click on: app ->res ->drawable(right click) ->New ->Drawable resource file and name it anything you want.
- Adding code to the resource file: Now that we have this drawable resource file, we can customize our button by adding tags like shape, color, stroke, or any other attribute which we want.