Основы верстки для нативных андроид приложений
( пользоваться не рекомендуется, deprecated )
AbsoluteLayout — означает что каждый элемент верстки будет иметь абсолютную позицию относительно верхнего левого угла экрана задаваемую с помощью координат x и y. Т.е. верхнийлевый угол экрана при AbsoluteLayout имеет координаты x = 0, y = 0.
Позиция указывается в атрибутах элемента android:layout_x и android:layout_y.
Пример кода:
FrameLayout
FrameLayout — тип верстки внутри которого может отображаться только один элемент в строке. Т.е. если внутри FrameLayout вы поместите несколько элементов, то следующий будет отображаться поверх предыдущего.
Пример кода:
LinearLayout
LinearLayout — тип верстки при котором область верстки делится на строки и в каждую строку помещается один элемент. Разбиение может быть вертикальное или горизонтальное, тип разбиения указывается в атрибуте LinearLayout android:orientation. Внутри верстки возможно комбинировать вертикальную и горизонтальную разбивки, а кроме того, возможна комбинация нескольких разных типов верстки например использование LinearLayout внутри FrameLayout.
Пример вертикальной разбивки LinearLayout:
Пример горизонтальной разбивки LinearLayout:
Комбинация нескольких LinearLayout:
RelativeLayout
RelativeLayout — тип верстки при котором позиционирование элементов происходит относительно друг друга и относительно главного контейнера.
За то, каким образом будут позиционироваться элементы отвечают следующие атрибуты:
Атрибуты позиционирования относительно контейнера
- android:layout_alignParentBottom – Низ элемента находится внизу контейнера
- android:layout_alignParentLeft – Левая часть элемента прилегает к левой части контейнера
- android:layout_alignParentRight – Правая часть элемента прилегает к правой части контейнера
- android:layout_alignParentTop – Элемент находится в верхней части контейнера
- android:layout_centerHorizontal – Элемент позиционируется по центру относительно горизонтального размера контейнера
- android:layout_centerInParent – Элемент позиционируется по центру относительно горизонтального и вертикального размеров размера контейнера
- android:layout_centerVertical – Элемент позиционируется по центру относительно вертикального размера контейнера
Атрибуты позиционирования относительно других элементов.
В качестве значений этих атрибутов ставятся id элемента относительно которого будет производится позиционирование.
android:layout_above – Распологает элемент над указанным
android:layout_below – Распологает элемент под указанным
android:layout_toLeftOf – Распологает элемент слева от указанного
android:layout_toRightOf – Распологает элемент справа от указанного
Выравнивание относительно других элементов.
android:layout_alignBaseline – Выравнивает baseline элемента с baseline указаннго элемента
android:layout_alignBottom – Выравнивает низ элемента по низу указанного элемента
android:layout_alignLeft – Выравнивает левый край элемента с левым краем указанного элемента
android:layout_alignRight – Выравнивает правый край элемента с правым краем указанного элемента
android:layout_alignTop – Выравнивает верхнюю часть элемента в соответствие с верхней частью указанного элемента
TableLayout
TableLayout — табличная верстка.
Организует элементы в строки и столбцы таблицы.
Для организации строк служит таг
Alternate Layouts
Alternate Layouts — альтернативная верстка. Позволяет использовать различную верстку для различных ориентаций экрана.
XML для альтернативной верстки помещается в папки проекта:
res/layout-land – альтернативная верстка для landscape UI
res/layout-port –альтернативная верстка для portrait UI
res/lauout-square – альтернативная верстка для square UI
и перед тем как получить макет из res/lauout система проверяет наличие файлов в этих папках.
И в завершении немного о стилях.
Стили
Во первых стили элемента могут быть описаны в атрибутах самого элемента.
Например:
Кроме того стили можно вынести в отдельный xml файл и сохранить его в папке res/values/
Напимер:
Если мы вынесем стили в отдельный файл, то для описания стилей элемента будем использовать атрибут style.
Источник
Android button wrap content
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:
Источник