- Button (Кнопка)
- Общая информация
- Три способа обработки событий нажатий на кнопку
- Первый способ — атрибут onClick
- Второй способ — метод setOnClickListener()
- Третий способ — интерфейс OnClickListener
- Плодитесь и размножайтесь — это про кошек, а не про кнопки
- Сделать кнопку недоступной
- Сделать кнопку плоской
- Коснись меня нежно
- Получить текст с кнопки
- Дополнительное чтение
- Библиотеки
- Android button source code
Button (Кнопка)
Общая информация
Кнопка — один из самых распространенных элементов управления в программировании. Наследуется от TextView и является базовым классом для класса СompoundButton. От класса CompoundButton в свою очередь наследуются такие элементы как CheckBox, ToggleButton и RadioButton. В Android для кнопки используется класс android.widget.Button. На кнопке располагается текст и на кнопку нужно нажать, чтобы получить результат. Альтернативой ей может служить компонент ImageButton (android.widget.ImageButton), у которого вместо текста используется изображение.
В студии кнопка представлена компонентом Button в разделе Widgets. Управлять размером шрифта, цветом текста и другими свойствами можно через атрибут textAppearance, который задействует системные стили. Выпадающий список данного свойства содержит огромный перечень вариантов. Также вы можете вручную задать конкретные индивидуальные настройки через отдельные свойства.
Если вы растягиваете кнопку по всей ширине экрана (android:layout_width=»match_parent»), то дополнительно рекомендую использовать атрибут android:layout_margin (или родственные ему layout_marginRight и layout_marginLeft) для создания отступов от краев экрана (веб-мастера знакомы с этими терминами).
Так как кнопка является наследником TextView, то использует многие знакомые атрибуты: textColor, textSize и др.
Три способа обработки событий нажатий на кнопку
Если вы разместили на экране кнопку и будете нажимать на неё, то ничего не произойдёт. Необходимо написать код, который будет выполняться при нажатии. Существует несколько способов обработки нажатий на кнопку.
Первый способ — атрибут onClick
Относительно новый способ, специально разработанный для Android — использовать атрибут onClick (на панели свойств отображается как On Click):
Имя для события можно выбрать произвольное, но лучше не выпендриваться. Далее нужно прописать в классе активности придуманное вами имя метода, который будет обрабатывать нажатие. Метод должен быть открытым (public) и с одним параметром, использующим объект View. Вам нужно выучить пять слов для создания метода, а сам метод поместить в класс (если вы ещё путаетесь в структуре Java-кода, то вставьте метод перед последней фигурной скобкой):
Когда пользователь нажимает на кнопку, то вызывается метод onMyButtonClick(), который в свою очередь генерирует всплывающее сообщение.
Обратите внимание, что при подобном подходе вам не придётся даже объявлять кнопку через конструкцию (Button)findViewById(R.id.button1), так как Android сама поймёт, что к чему. Данный способ применим не только к кнопке, но и к другим элементам и позволяет сократить количество строк кода.
Второй способ — метод setOnClickListener()
Более традиционный способ в Java — через метод setOnClickListener(), который прослушивает нажатия на кнопку. Так как для начинающего программиста код может показаться сложным, то рекомендуется использовать подсказки студии. Вот как это будет выглядеть. Предположим, у вас на экране уже есть кнопка button. В коде вы объявляете её обычным способом:
Следующий шаг — написание метода для нажатия. Напечатайте имя элемента и поставьте точку button. — среда разработки покажет вам список доступных выражений для продолжения кода. Вы можете вручную просмотреть и выбрать нужный вариант, а можно продолжать набирать символы, чтобы ускорить процесс. Так как с нажатиями кнопок вам часто придётся работать, то запомните название его метода (хотя бы первые несколько символов) — набрав четыре символа (seto), вы увидите один оставшийся вариант, дальше можно сразу нажать клавишу Enter, не набирая оставшиеся символы. У вас появится строка такого вида:
Курсор будет находиться внутри скобок и появится подсказка OnClickListener l. Начинайте набирать new OnClickListener. Здесь также не обязательно набирать имя полностью. Набрав слово Oncl, вы увидете нужный вариант и снова нажимайте Enter. В результате вы получите готовую заготовку для обработки нажатия кнопки:
Теперь у вас есть рабочая заготовка и сразу внутри фигурных скобок метода onClick() вы можете писать свой код. Рекомендую потренироваться и набить руку в создании заготовки. Это не так сложно, и с практикой навык закрепится автоматически.
Как вариант, можно вынести код для OnClickListener в отдельное место, это удобно, когда кнопок на экране несколько и такой подход позволит упорядочить код. Удалите предыдущий пример и начните писать код заново. Принцип такой же, немного меняется порядок. В предыдущем примере мы сразу прописали в методе setOnClickListener слушателя new OnClickListener. с методом onClick(). Можно сначала отдельно объявить отдельную переменную myButtonClickListener:
Во время набора активно используйте подсказки через Ctrl+Space. Набрали несколько символов у первого слова и нажимайте эту комбинацию, набрали после слова new несколько символов и снова нажимайте указанную комбинацию — заготовка будет создана за несколько секунд, а вы избежите возможных опечаток.
У нас есть готовая переменная, и теперь, когда вы будете набирать код button.setOnClickListener, то вместо new OnClickListener впишите готовую переменную.
Для новичка описание может показаться сумбурным и не понятным, но лучше самостоятельно проделать эти операции и понять механизм.
Третий способ — интерфейс OnClickListener
Третий способ является родственным второму способу и также является традиционным для Java. Кнопка присваивает себе обработчика с помощью метода setOnClickListener (View.OnClickListener l), т.е. подойдет любой объект с интерфейсом View.OnClickListener. Мы можем указать, что наш класс Activity будет использовать интерфейс View.OnClickListener.
Опять стираем код от предыдущего примера. Далее после слов extends Activity дописываем слова implements OnClickListener. При появлении подсказки не ошибитесь. Обычно первым идёт интерфейс для диалогов, а вторым нужный нам View.OnClickListener.
Название вашего класса будет подчёркнуто волнистой красной чертой, щёлкните слово public и дождитесь появления красной лампочки, выберите вариант Implement methods. Появится диалоговое окно с выделенным методом onClick. Выбираем его и в коде появится заготовка для нажатия кнопки.
Метод будет реализован не в отдельном объекте-обработчике, а в Activity, который и будет выступать обработчиком. В методе onCreate() присвоим обработчик кнопке. Это будет объект this, т.е. текущий объект нашей активности.
На первых порах такой способ также покажется вам сложным и непонятным. Со временем и опытом понимание обязательно придёт.
Лично я рекомендую вам использовать первый способ, как самый простой и понятный. Использование второго и третьего способа дадут вам представление, как писать обработчики для других событий, так как кнопка может иметь и другие события. Например, кроме обычного нажатия существует долгое нажатие на кнопку (long click). Один из таких примеров с методом касания я привёл в конце этой статьи.
О том, как обрабатывать щелчки кнопки я написал отдельную статью Щелчок кнопки/Счетчик ворон. Также кнопки часто будут встречаться во многих примерах на сайте. Про обработку длительный нажатий можно прочитать в статье, посвященной ImageButton.
Плодитесь и размножайтесь — это про кошек, а не про кнопки
Когда у вас одна кнопка в окне, то у вас будет один метод, две кнопки — два метода и так далее. Если у вас несколько кнопок, то не обязательно для каждой прописывать свой метод, можно обойтись и одним, а уже в самом методе разделять код по идентификатору кнопки. Если вы посмотрите на код в предыдущих примерах, то увидите, что в методе присутствует параметр View, который и позволяет определить, для какой кнопки предназначен кусок кода:
Предположим, у вас есть три кнопки:
Как видите, мы сократили количество кода. Теперь у нас один обработчик onClick(), в котором прописаны действия для трёх кнопок.
Сделать кнопку недоступной
Иногда нужно сделать кнопку недоступной и активировать её при определённых условиях. Через XML нельзя сделать кнопку недоступной (нет подходящего атрибута). Это можно сделать программно через метод setEnabled():
Как альтернативу можете рассмотреть атрибут android:clickable, который позволит кнопке не реагировать на касания, но при этом вид кнопки останется обычным.
Сделать кнопку плоской
Стандартная кнопка на экране выглядит выпуклой. Но в некоторых случаях желательно использовать плоский интерфейс. Раньше для этих целей можно было использовать TextView с обработкой щелчка. Но теперь рекомендуют использовать специальный стиль borderlessButtonStyle:
Кнопка сохранит своё привычное поведение, будет менять свой цвет при нажатии и т.д.
С появлением Material Design добавились другие стили, например, style=»@style/Widget.AppCompat.Button.Borderless», который является предпочтительным вариантом. Попробуйте также style=»@style/Widget.AppCompat.Button.Borderless.Colored»
Коснись меня нежно
Если вы внимательно понаблюдаете за поведением кнопки, то увидите, что код срабатывает в тот момент, когда вы отпускаете свою лапу, извините, палец с кнопки. Для обычных приложений это вполне нормально, а для игр на скорость такой подход может оказаться слишком медленным. В подобных случаях лучше обрабатывать ситуацию не с нажатием кнопки, а с его касанием. В Android есть соответствующий слушатель OnTouchListener():
У метода onTouch() есть параметр MotionEvent, позволяющий более тонко определять касания экрана. Если произойдет событие, когда пользователь коснулся экрана, то ему будет соответствовать константа ACTION_DOWN. Соответственно, если пользователь уберёт палец, то нужно использовать константу ACTION_UP. Таким образом, можете расценивать щелчок кнопки как комбинацию двух событий — касания и отпускания.
Получить текст с кнопки
Навеяно вопросом с форума. Задача — получить текст кнопки в методе onClick(). У метода есть параметр типа View, у которого нет метода getText(). Для этого нужно привести тип к типу Button.
Если у вас несколько кнопок привязаны к методу onClick(), то щелчок покажет текст нажатой кнопки.
Дополнительное чтение
SwipeButton — кнопка с поддержкой свайпа
Библиотеки
dmytrodanylyk/circular-progress-button — ещё один вариант кнопок с индикатором прогресса.
Источник
Android button source code
Buttons allow users to take actions, and make choices, with a single tap.
Contents
Before you can use Material buttons, you need to add a dependency to the Material Components for Android library. For more information, go to the Getting started page.
Note: is auto-inflated as via MaterialComponentsViewInflater when using a Theme.Material3.* theme.
Making buttons accessible
Buttons support content labeling for accessibility and are readable by most screen readers, such as TalkBack. Text rendered in buttons is automatically provided to accessibility services. Additional content labels are usually unnecessary.
For more information on content labels, go to the Android accessibility help guide.
Toggle button is an additional pattern using a segmented container or icon.
Elevated buttons are essentially outlined buttons with a shadow. To prevent shadow creep, only use them when absolutely necessary, such as when the button requires visual separation from a patterned background.
Elevated button examples
API and source code:
The following example shows an elevated button with a text label.
Adding an icon to an elevated button
The following example shows an elevated button with an icon.
Anatomy and key properties
An elevated button has a text label, a stroked container and an optional icon.
Text label attributes
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Text label | android:text | setText getText | null |
Color | android:textColor | setTextColor getTextColor | ?attr/colorOnSurface (see all states) |
Typography | android:textAppearance | setTextAppearance | ?attr/textAppearanceLabelLarge |
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Color | app:backgroundTint | setBackgroundColor setBackgroundTintList getBackgroundTintList | ?attr/colorSurface (see all states) |
Stroke color | app:strokeColor | setStrokeColor setStrokeColorResource getStrokeColor | null |
Stroke width | app:strokeWidth | setStrokeWidth setStrokeWidthResource getStrokeWidth | 0dp |
Shape | app:shapeAppearance | setShapeAppearanceModel getShapeAppearanceModel | ?attr/shapeAppearanceSmallComponent |
Elevation | app:elevation | setElevation getElevation | 1dp |
Ripple color | app:rippleColor | setRippleColor setRippleColorResource getRippleColor | ?attr/colorOnSurface at 16% opacity (see all states) |
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Icon | app:icon | setIcon setIconResource getIcon | null |
Color | app:iconTint | setIconTint setIconTintResource getIconTint | ?attr/colorOnSurface (see all states) |
Size | app:iconSize | setIconSize getIconSize | wrap_content |
Gravity (position relative to text label) | app:iconGravity | setIconGravity getIconGravity | start |
Padding (space between icon and text label) | app:iconPadding | setIconPadding getIconPadding | 8dp |
Element | Style |
---|---|
Default style | Widget.Material3.Button.ElevatedButton |
Icon style | Widget.Material3.Button.ElevatedButton.Icon |
See the full list of styles and attrs.
Filled button’s contrasting surface color makes it the most prominent button after the FAB. It’s used for final or unblocking actions in a flow.
Note The filled button is the default style if the style is not set.
Filled button examples
API and source code:
The following example shows a filled button with a text label and a filled container.
Note: Since this is the default type, you don’t need to specify a style tag as long as you are using a Material Components Theme. If not, set the style to @style/Widget.Material3.Button .
Adding an icon to a filled button
The following example shows a filled button with an icon.
Anatomy and key properties
A filled button has a text label, a filled container and an optional icon.
Text label attributes
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Text label | android:text | setText getText | null |
Color | android:textColor | setTextColor getTextColor | ?attr/colorOnPrimary (see all states) |
Typography | android:textAppearance | setTextAppearance | ?attr/textAppearanceLabelLarge |
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Color | app:backgroundTint | setBackgroundColor setBackgroundTintList getBackgroundTintList | ?attr/colorPrimary (see all states) |
Stroke color | app:strokeColor | setStrokeColor setStrokeColorResource getStrokeColor | null |
Stroke width | app:strokeWidth | setStrokeWidth setStrokeWidthResource getStrokeWidth | 0dp |
Shape | app:shapeAppearance | setShapeAppearanceModel getShapeAppearanceModel | ?attr/shapeAppearanceSmallComponent |
Elevation | app:elevation | setElevation getElevation | 2dp |
Ripple color | app:rippleColor | setRippleColor setRippleColorResource getRippleColor | ?attr/colorOnPrimary at 16% opacity (see all states) |
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Icon | app:icon | setIcon setIconResource getIcon | null |
Color | app:iconTint | setIconTint setIconTintResource getIconTint | ?attr/colorOnPrimary (see all states) |
Size | app:iconSize | setIconSize getIconSize | wrap_content |
Gravity (position relative to text label) | app:iconGravity | setIconGravity getIconGravity | start |
Padding (space between icon and text label) | app:iconPadding | setIconPadding getIconPadding | 8dp |
Element | Style |
---|---|
Default style | Widget.Material3.Button |
Icon style | Widget.Material3.Button.Icon |
Unelevated style | Widget.Material3.Button.UnelevatedButton |
Unelevated icon style | Widget.Material3.Button.UnelevatedButton.Icon |
Default style theme attribute: ?attr/materialButtonStyle
See the full list of styles and attrs.
Filled tonal button
Filled tonal buttons have a lighter background color and darker label color, making them less visually prominent than a regular filled button. They’re still used for final or unblocking actions in a flow, but may be better when these actions don’t require quite so much emphasis.
Filled tonal button examples
API and source code:
The following example shows a filled tonal button with a text label and a filled container.
Adding an icon to a filled tonal button
The following example shows a filled tonal button with an icon.
Anatomy and key properties
A filled tonal button has a text label, a filled container and an optional icon.
Text label attributes
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Text label | android:text | setText getText | null |
Color | android:textColor | setTextColor getTextColor | ?attr/colorOnSecondaryContainer (see all states) |
Typography | android:textAppearance | setTextAppearance | ?attr/textAppearanceLabelLarge |
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Color | app:backgroundTint | setBackgroundColor setBackgroundTintList getBackgroundTintList | ?attr/colorSecondaryContainer (see all states) |
Stroke color | app:strokeColor | setStrokeColor setStrokeColorResource getStrokeColor | null |
Stroke width | app:strokeWidth | setStrokeWidth setStrokeWidthResource getStrokeWidth | 0dp |
Shape | app:shapeAppearance | setShapeAppearanceModel getShapeAppearanceModel | ?attr/shapeAppearanceSmallComponent |
Elevation | app:elevation | setElevation getElevation | 2dp |
Ripple color | app:rippleColor | setRippleColor setRippleColorResource getRippleColor | ?attr/colorOnSecondaryContainer at 16% opacity (see all states) |
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Icon | app:icon | setIcon setIconResource getIcon | null |
Color | app:iconTint | setIconTint setIconTintResource getIconTint | ?attr/colorOnSecondaryContainer (see all states) |
Size | app:iconSize | setIconSize getIconSize | wrap_content |
Gravity (position relative to text label) | app:iconGravity | setIconGravity getIconGravity | start |
Padding (space between icon and text label) | app:iconPadding | setIconPadding getIconPadding | 8dp |
Element | Style |
---|---|
Default style | Widget.Material3.Button.TonalButton |
Icon style | Widget.Material3.Button.TonalButton.Icon |
See the full list of styles and attrs.
Outlined buttons are for actions that need attention but aren’t the primary action, such as “See all” or “Add to cart.” This is also the button used to give someone the opportunity to change their mind or escape a flow.
Outlined button examples
API and source code:
The following example shows an outlined button with a text label and stroked container.
Adding an icon to an outlined button
The following example shows an outlined button with an icon.
Anatomy and key properties
An outlined button has a text label, a stroked container and an optional icon.
Text label attributes
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Text label | android:text | setText getText | null |
Color | android:textColor | setTextColor getTextColor | ?attr/colorOnSurface (see all states) |
Typography | android:textAppearance | setTextAppearance | ?attr/textAppearanceLabelLarge |
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Color | app:backgroundTint | setBackgroundColor setBackgroundTintList getBackgroundTintList | @android:color/transparent (see all states) |
Stroke color | app:strokeColor | setStrokeColor setStrokeColorResource getStrokeColor | ?attr/colorOnSurface at 12% opacity (see all states) |
Stroke width | app:strokeWidth | setStrokeWidth setStrokeWidthResource getStrokeWidth | 1dp |
Shape | app:shapeAppearance | setShapeAppearanceModel getShapeAppearanceModel | ?attr/shapeAppearanceSmallComponent |
Elevation | app:elevation | setElevation getElevation | 0dp |
Ripple color | app:rippleColor | setRippleColor setRippleColorResource getRippleColor | ?attr/colorOnSurface at 16% opacity (see all states) |
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Icon | app:icon | setIcon setIconResource getIcon | null |
Color | app:iconTint | setIconTint setIconTintResource getIconTint | ?attr/colorOnSurface (see all states) |
Size | app:iconSize | setIconSize getIconSize | wrap_content |
Gravity (position relative to text label) | app:iconGravity | setIconGravity getIconGravity | start |
Padding (space between icon and text label) | app:iconPadding | setIconPadding getIconPadding | 8dp |
Element | Style |
---|---|
Default style | Widget.Material3.Button.OutlinedButton |
Icon style | Widget.Material3.Button.OutlinedButton.Icon |
Default style theme attribute: ?attr/materialButtonOutlinedStyle
See the full list of styles and attrs.
Text buttons have less visual prominence, so should be used for low emphasis actions, such as when presenting multiple options.
Text button examples
API and source code:
The following example shows a text button with a text label.
Adding an icon to a text button
The following example shows a text button with an icon.
Anatomy and key properties
A text button has a text label, a transparent container and an optional icon.
Text label attributes
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Text label | android:text | setText getText | null |
Color | android:textColor | setTextColor getTextColor | ?attr/colorOnSurface (see all states) |
Typography | android:textAppearance | setTextAppearance | ?attr/textAppearanceLabelLarge |
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Color | app:backgroundTint | setBackgroundColor setBackgroundTintList getBackgroundTintList | @android:color/transparent (see all states) |
Stroke color | app:strokeColor | setStrokeColor setStrokeColorResource getStrokeColor | null |
Stroke width | app:strokeWidth | setStrokeWidth setStrokeWidthResource getStrokeWidth | 0dp |
Shape | app:shapeAppearance | setShapeAppearanceModel getShapeAppearanceModel | ?attr/shapeAppearanceSmallComponent |
Elevation | app:elevation | setElevation getElevation | 0dp |
Ripple color | app:rippleColor | setRippleColor setRippleColorResource getRippleColor | ?attr/colorOnSurface at 16% opacity (see all states) |
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Icon | app:icon | setIcon setIconResource getIcon | null |
Color | app:iconTint | setIconTint setIconTintResource getIconTint | ?attr/colorOnSurface (see all states) |
Size | app:iconSize | setIconSize getIconSize | wrap_content |
Gravity (position relative to text label) | app:iconGravity | setIconGravity getIconGravity | start |
Padding (space between icon and text label) | app:iconPadding | setIconPadding getIconPadding | 8dp |
Element | Style |
---|---|
Default style | Widget.Material3.Button.TextButton |
Icon style | Widget.Material3.Button.TextButton.Icon |
Full Width Buttons | Widget.Material3.Button.TextButton.Dialog.FullWidth |
Default style theme attribute: ?attr/borderlessButtonStyle
See the full list of styles and attrs.
Toggle buttons can be used to select from a group of choices.
There are two types of toggle buttons:
To emphasize groups of related toggle buttons, a group should share a common container.
Toggle button examples
API and source code:
The following example shows a toggle button with three buttons that have text labels.
Implementing an icon-only toggle button
The following example shows a toggle button with three buttons that have icons.
Anatomy and key properties
A toggle button has a shared stroked container, icons and/or text labels.
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Single selection | app:singleSelection | setSingleSelection isSingleSelection | false |
Selection required | app:selectionRequired | setSelectionRequired isSelectionRequired | false |
Element | Style |
---|---|
Default style | Widget.Material3.MaterialButtonToggleGroup |
Default style theme attribute: ?attr/materialButtonToggleGroupStyle
See the full list of styles and attrs.
Icons can be used as toggle buttons when they allow selection, or deselection, of a single choice, such as marking an item as a favorite.
API and source code:
Note The CheckBox API is just one of several inputs that can implement the icon button. See other selection controls for more details.
The following example shows an icon that can be used independently or in items of a RecyclerView .
Buttons support Material Theming and can be customized in terms of color, typography and shape.
Button theming example
API and source code:
The following example shows text, outlined and filled button types with Material Theming.
Implementing button theming
Use theme attributes and styles in res/values/styles.xml to add the theme to all buttons. This affects other components:
Use default style theme attributes, styles and theme overlays. This adds the theme to all buttons but does not affect other components:
Use one of the styles in the layout. That will affect only this button:
Источник