Changing button color android studio

Change colour of button in Android Studio

As you know, the Default color of the button in the android studio is grey which is not suits for UI. So, here we are going to discuss how to change the colour of the button in android studio using different methods

Table of Contents

Method 1: Using XML

First, add the button in XML layout like this

Normal color of button

After this you will see your button looks something like this

Now you need to add another tag that is android:background=”color Hexa code” like this,

Now, you see your button looks like this

coloured color of button

Method 2: Using a drawable file

This is my best method because it provides you many other operations to perform on the button like rounded corner etc.

Right click on drawable -> new-> drawable resource file and named as background.

Add following line of code there

You see something like this

drawable file

Now, goto your button and drawable like this

coloured button

We update this content as we see more and more methods to change the colour of button in android studio.

How to add button in android studio?

Simply add from the design section of XML layout.

How to change the colour of button in android studio?

Add android:background=”colour” in button

Источник

How to Change the Background Color of Button in Android using ColorStateList?

ColorStateList is an object which can define in an XML file that can be used to apply different colors on widgets (such as Buttons, etc) depending on the state of Widgets to which it is being applied. For Example, There are many states of Buttons like (pressed, focussed, or none of them ) and other widgets states like enable, checkable, checked, etc, Using Color State List is a nice way to change the color of the button without using shape drawables or custom images. One should remember the color state list can be used anywhere, where color is used. The color state list is defined in XML and saved under the res/color folder. The root element of the color state list is a selector and the item element is defined for each state that you want to define the color by using color and alpha attributes. The default color should be the last element which is used when color for a specific state is not defined. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.

Читайте также:  Man in the middle android wifi

Approach

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Источник

Делаем красивые кнопки в 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 в случае, если здесь изображение не нужно).

Источник

Buttons

A button consists of text or an icon (or both text and an icon) that communicates what action occurs when the user touches it.

Depending on whether you want a button with text, an icon, or both, you can create the button in your layout in three ways:

  • With text, using the Button class:
  • With an icon, using the ImageButton class:
  • With text and an icon, using the Button class with the android:drawableLeft attribute:

Key classes are the following:

Responding to Click Events

When the user clicks a button, the Button object receives an on-click event.

To define the click event handler for a button, add the android:onClick attribute to the element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.

Читайте также:  Перенос календаря android с ios

For example, here’s a layout with a button using android:onClick :

Within the Activity that hosts this layout, the following method handles the click event:

Kotlin

The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:

  • Be public
  • Return void
  • Define a View as its only parameter (this will be the View that was clicked)

Using an OnClickListener

You can also declare the click event handler programmatically rather than in an XML layout. This might be necessary if you instantiate the Button at runtime or you need to declare the click behavior in a Fragment subclass.

To declare the event handler programmatically, create an View.OnClickListener object and assign it to the button by calling setOnClickListener(View.OnClickListener) . For example:

Kotlin

Styling Your Button

The appearance of your button (background image and font) may vary from one device to another, because devices by different manufacturers often have different default styles for input controls.

You can control exactly how your controls are styled using a theme that you apply to your entire application. For instance, to ensure that all devices running Android 4.0 and higher use the Holo theme in your app, declare android:theme=»@android:style/Theme.Holo» in your manifest’s element. Also read the blog post, Holo Everywhere for information about using the Holo theme while supporting older devices.

To customize individual buttons with a different background, specify the android:background attribute with a drawable or color resource. Alternatively, you can apply a style for the button, which works in a manner similar to HTML styles to define multiple style properties such as the background, font, size, and others. For more information about applying styles, see Styles and Themes.

Borderless button

One design that can be useful is a «borderless» button. Borderless buttons resemble basic buttons except that they have no borders or background but still change appearance during different states, such as when clicked.

To create a borderless button, apply the borderlessButtonStyle style to the button. For example:

Custom background

If you want to truly redefine the appearance of your button, you can specify a custom background. Instead of supplying a simple bitmap or color, however, your background should be a state list resource that changes appearance depending on the button’s current state.

You can define the state list in an XML file that defines three different images or colors to use for the different button states.

To create a state list drawable for your button background:

    Create three bitmaps for the button background that represent the default, pressed, and focused button states.

To ensure that your images fit buttons of various sizes, create the bitmaps as Nine-patch bitmaps.

Источник

Оцените статью