Style android attr buttonbarstyle

Стили

Панель навигации

Делаем панель навигации прозрачной (API 19+)

По умолчанию панель навигации с кнопками «Назад», «Домой» и «Недавние программы» имеет чёрный цвет. Переопределяем (API 21+).

Строка состояния

Можно поменять на Android 5 (Lollipop).

Позже (API 21+) можно уже не указывать targetApi.

Делаем строку состояния прозрачной (API 19+).

Меняем цвет строку состояния на белый (API 23+).

Программный способ (API 21++).

Переопределяем внешний вид стандартного значка меню в виде трёх точек по вертикальной линии.

Читатели сообщили, что код может не работать и дали ссылку на работающий вариант:

Кнопки

Обычная кнопка по умолчанию использует стиль 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 позволяет использовать анимацию. В противном случае значок будет статичным.

Источник

Как создать стандартные кнопки без полей (как в упомянутом руководстве по дизайну)?

Я просто проверял рекомендации по дизайну и задавался вопросом о кнопках без полей. Я вытаращил глаза и попытался найти в источнике, но не смог собрать его самостоятельно. Это обычный виджет Button, но вы добавляете собственный стиль (по умолчанию для Android)? Как сделать эти кнопки без полей (конечно, вы можете сделать фон пустым, но тогда у меня нет разделителя)?

Здесь ссылки на рекомендации по дизайну:

Чтобы устранить некоторую путаницу:

Это делается в два шага: Установка атрибута фона кнопки на android: attr / selectableItemBackground создает кнопку с обратной связью, но без фона.

Линия, отделяющая кнопку без полей от остального макета, выполняется представлением с фоном android: attr / dividerVertical

Для лучшего понимания вот макет для комбинации кнопок ОК / Отмена без полей в нижней части экрана (как на правом рисунке выше).

Просто добавьте в свой Button тег следующий атрибут стиля :

Читайте также:  Is there bbm on android

Затем вы можете добавить разделители, как в ответе Карла .

Поздний ответ, но много просмотров. Поскольку API android:background=»@drawable/selector_transparent_button»

PS: пусть у вас есть разделители в контейнере ( android:divider=’@android:drawable/. для API — аакотронео
источник

Для тех, кому нужны кнопки без полей, но все еще анимированные при нажатии. Добавьте это в кнопку.

Если вам нужен разделитель / линия между ними. Добавьте это в линейный макет.

Для стиля материала добавьте style=»@style/Widget.AppCompat.Button.Borderless» при использовании библиотеки AppCompat.

Из источника приложения iosched я придумал этот ButtonBar класс:

Это будет то, LinearLayout что нужно для кнопок «ОК» и «Отмена», и будет обрабатывать их размещение в соответствующем порядке. Затем поместите это в макет, в котором вы хотите разместить кнопки:

Это дает вам вид диалога с кнопками без полей. Вы можете найти эти атрибуты в разрешении во фреймворке. buttonBarStyle делает вертикальный разделитель и отступ. buttonBarButtonStyle установлен как borderlessButtonStyle для темы Holo, но я считаю, что это должен быть наиболее надежный способ ее отображения, поскольку платформа хочет ее отображать.

Посмотрите в тему атрибутов buttonBarStyle , buttonBarButtonStyle и borderlessButtonStyle .

Вы также можете сделать кнопки без полей с помощью кода:

Источник

Установка стиль=»?android:attr/buttonBarStyle» родительского макета и стиля=»?android:attr/buttonBarButtonStyle» кнопки, чтобы сделать их незаметными

Я последовал рекомендации Android и установил style=»?android:attr/buttonBarStyle» в родительский макет, а style=»?android:attr/buttonBarButtonStyle» -в кнопки.

Так что теперь мой макет выглядит примерно так:

Но после установки стиля эти кнопки стали невидимыми, хотя я все еще могу нажимать на них.

Пожалуйста, скажи мне, что случилось.

Правка: дополнительные сведения

Ну, я только что создал новый проект специально для тестирования этого макета, и удивительно, что он действительно работает.

Поэтому, чтобы быть более точным, на самом деле я динамически добавляю этот макет к другому, что-то вроде этого:

Извините, что не упомянул об этом раньше, но я не думал, что это может быть так.

Так в чем же дело?

2 ответа

У меня возникли некоторые проблемы со встроенным стилем панели кнопок Android. После того как я дал ширину 0 и вес 1 каждой из моих кнопок, между ними все еще остается примерно 1px зазор (см. изображение). Каков наилучший способ избавиться от этого разрыва? Почему она вообще существует.

Я хотел бы знать, как эти теги работают в android xml, например, в стилизации style=?android:attr/buttonBarButtonStyle и style=@android:attr/buttonBarButtonStyle Я пытался узнать себя, но эти теги дали мне почти такой же результат в моем предыдущем проекте. однако четкого ответа в интернете найти.

Мне просто нужно было использовать

Приведенный пример работает и для меня. В поисках этого атрибута стиля я нашел следующий пример: https://developer.android.com/samples/BorderlessButtons/res/layout/sample_main.html Здесь вы можете прочитать, как применить стиль к каждой кнопке, что вы и сделали в приведенном примере. Таким образом, я подразумеваю, что что-то закрывает ваши кнопки или текст на кнопке имеет белый цвет (или цвет фона вашего приложения).

Похожие вопросы:

В большинстве примеров для кнопок ICS+, а именно в этом примере инженера Google: https://gist.github.com/2357306 Я вижу ссылку на эти стили: style=?android:attr/buttonBarStyle.

Я пытаюсь построить Android UI с помощью макетов. Я начинаю со следующего:

Я пытаюсь стилизовать кнопки так, чтобы они выглядели так же, как те, о которых я спрашиваю, в стиле Android Full Width ICS Minimalist Bottom ButtonsViews . У меня получилось, со следующими xml для.

У меня возникли некоторые проблемы со встроенным стилем панели кнопок Android. После того как я дал ширину 0 и вес 1 каждой из моих кнопок, между ними все еще остается примерно 1px зазор (см.

Я хотел бы знать, как эти теги работают в android xml, например, в стилизации style=?android:attr/buttonBarButtonStyle и style=@android:attr/buttonBarButtonStyle Я пытался узнать себя, но эти теги.

Недавно я попытался применить подход, основанный на стиле, к моему приложению android. Однако я застрял с этой дилеммой. В моем файле макета у меня изначально было вот это:

Переопределение цвета текста для кнопок не работает

Читайте также:  Что можно взломать с помощью андроида

Я создал пользовательскую тему для панели кнопок, используя buttonBarStyle на каждой кнопке и buttonBarButtonStyle на макете. Он работает нормально, но я хочу изменить цвет текста для кнопок, но он.

Я только что начал с Android и имею следующий код. Я хочу показать три кнопки в нижней части экрана, не меняя их на относительный макет. Я попытался установить layout_weight и gravity внутренней.

Я устанавливаю некоторые значения по умолчанию styles для своего приложения, и я хотел бы иметь ?android:attr/textAppearanceMedium в качестве родителя style . но я не могу, Android Studio жалуется.

Я открыл проект android, получил эту ошибку, как ее исправить? Information:Gradle задачи [очистить, :app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar] Свойство.

Источник

Android styling: common theme attributes

In the previous article in this series on Android styling, we looked at the difference between themes and styles and how themes allow you to write more flexible styles and layouts which isolate changes:

Android Styling: Themes vs Styles

The Android styling system offers a powerful way to specify your app’s visual design, but it can be easy to misuse…

Specifically we recommended using theme attributes to provide a point of indirection to resources, so that you can vary them (e.g. in dark theme). That is, if you find yourself writing a direct resource reference (or worse yet, a hardcoded value 😱) in a layout or style, consider if you should use a theme attribute instead.

But what theme attributes are available to use? This post highlights the common ones that you should know about; those that come from Material, AppCompat or the platform. This is not a complete list (for that I’d recommend browsing the attrs files linked below where they are defined) but these are the attributes that I use all the time.

Colors

Many of these colors come from the Material color system, which defines semantic names for colors that you can use throughout your app (implemented as theme attrs).

  • ?attr/colorPrimary The primary branding color for the app.
  • ?attr/colorSecondary The secondary branding color for the app, usually a bright complement to the primary branding color.
  • ?attr/colorOn[Primary, Secondary, Surface etc] A color which contrasts against the named color.
  • ?attr/color[Primary, Secondary]Variant An alternate shade of the given color.
  • ?attr/colorSurface A color for surfaces of components, such as cards, sheets, and menus.
  • ?android:attr/colorBackground The background for the screen.
  • ?attr/colorPrimarySurface switches between colorPrimary in the Light themes, colorSurface in the Dark theme.
  • ?attr/colorError A color for displaying errors.

Other handy colors:

  • ?attr/colorControlNormal The color applied to icons/controls in their normal state.
  • ?attr/colorControlActivated The color applied to icons/controls in their activated state (e.g. checked).
  • ?attr/colorControlHighlight The color applied to control highlights (e.g. ripples, list selectors).
  • ?android:attr/textColorPrimary The most prominent text color.
  • ?android:attr/textColorSecondary Secondary text color.

Dimens

  • ?attr/listPreferredItemHeight Standard (min) height for list items.
  • ?attr/actionBarSize The height of a toolbar.

Drawables

  • ?attr/selectableItemBackground A ripple/highlight for interactive items (also handy for foregrounds!!)
  • ?attr/selectableItemBackgroundBorderless An unbounded ripple.
  • ?attr/dividerVertical A drawable that may be used as a vertical divider between visual elements.
  • ?attr/dividerHorizontal A drawable that may be used as a horizontal divider between visual elements.

TextAppearances

Material defines a type scale — a discrete set of text styles that you should use throughout your app, each of which is provided as a theme attribute which can be set as a textAppearance . Check out the Material type scale generator to help generate a scale for different fonts.

  • ?attr/textAppearanceHeadline1 defaults to light 96sp text.
  • ?attr/textAppearanceHeadline2 defaults to light 60sp text.
  • ?attr/textAppearanceHeadline3 defaults to regular 48sp text.
  • ?attr/textAppearanceHeadline4 defaults to regular 34sp text.
  • ?attr/textAppearanceHeadline5 defaults to regular 24sp text.
  • ?attr/textAppearanceHeadline6 defaults to medium 20sp text.
  • ?attr/textAppearanceSubtitle1 defaults to regular 16sp text.
  • ?attr/textAppearanceSubtitle2 defaults to medium 14sp text.
  • ?attr/textAppearanceBody1 defaults to regular 16sp text.
  • ?attr/textAppearanceBody2 defaults to regular 14sp text.
  • ?attr/textAppearanceCaption defaults to regular 12sp text.
  • ?attr/textAppearanceButton defaults to medium all caps 14sp text.
  • ?attr/textAppearanceOverline defaults to regular all caps 10sp text.
Читайте также:  Создать мелодию для андроид

Shape

Material employs a shape system which is implemented as theme attrs for small, medium and large components. Note that if you’re setting a shape appearance on a custom component, you likely want to use a MaterialShapeDrawable as it’s background which understands and implements the shaping.

  • ?attr/shapeAppearanceSmallComponent used for Buttons, Chips, Text Fields etc. Defaults to rounded 4dp corners.
  • ?attr/shapeAppearanceMediumComponent used for Cards, Dialogs, Date Pickers etc. Defaults to rounded 4dp corners.
  • ?attr/shapeAppearanceLargeComponent used for Bottom Sheets etc. Defaults to rounded 0dp corners (i.e. square!)

Button Styles

This might seem super specific, but Material defines three types of buttons: Contained, Text and Outlined. MDC offers theme attrs that you can use to set the style of a MaterialButton :

  • ?attr/materialButtonStyle defaults to contained (or just omit the style).
  • ?attr/borderlessButtonStyle for a text style button.
  • ?attr/materialButtonOutlinedStyle for outlined style.

Floats

  • ?android:attr/disabledAlpha Default disabled alpha for widgets.
  • ?android:attr/primaryContentAlpha The alpha applied to the foreground elements.
  • ?android:attr/secondaryContentAlpha The alpha applied to secondary elements.

App vs Android namespace

You might have noticed that some attributes are referenced by
? android:attr/foo and others just by ?attr/bar . This is because some are defined by the Android platform, and as such you need the android part to reference them by their namespace (just like with view attributes in layouts: android:id ). Those without come from static libraries (i.e. AppCompat or MDC) which are compiled into your application, so don’t need the namespace (similar to how you might use app:baz in a layout). Some elements are defined both in the platform and in a library e.g. colorPrimary . In these cases, prefer the non-platform version, as this can be used on all API levels i.e. they’re duplicated in a library precisely to backport them. In these cases, I’ve listed the non-platform versions above.

prefer non-platform attributes which can be used on all API levels

More Resources

For a complete list of the theme attributes available to use, go to the source of truth:

Material Design Components:

Do It Yourself

Sometimes there isn’t a theme attribute which abstracts something you’d like to vary by theme. No worries… create your own! Here’s an example from the Google I/O app which shows a list of conference sessions in two screens.

They’re largely similar but the left screen must leave space for the sticky time headers while the right screen does not. We implemented this by abstracting where to align items behind a theme attribute so that we can vary them by theme and use the same layout across two different screens:

1. Define the theme attribute in attrs.xml

2. Provide different values in different themes:

3. Use the theme attr in the single layout used on both screens (each using one of the above themes):

Question (mark) everything

Knowing what theme attributes are available, equips you to use them when writing your layouts, styles or drawables. Using theme attributes makes it much easier to support theming (like dark theme) and to write more flexible, maintainable code. For a deep dive on this, join us in our next post in this series:

Источник

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