- Темы и стили в Android без магии. И как их готовить с SwitchCompat
- Содержание
- Введение
- Новый стиль для SwitchCompat
- Стиль в верстке
- Стиль в теме. Тема назначается через Manifest
- Стиль в теме. Тема назначается программно
- Другие View
- Ресурсы
- romannurik / AndroidManifest.xml
- This comment has been minimized.
- jrub commented Jun 24, 2015
- This comment has been minimized.
- ursusursus commented Feb 19, 2016
- Android: set view style programmatically
- Related Posts
- android – How do I display a CalendarView in an AlertDialog?
- How do I convert a PSD design to Android xml?
- Android: установить стиль просмотра программно
- How to programmatically setting style attribute in a view
Темы и стили в Android без магии. И как их готовить с SwitchCompat
В предыдущей статье мы рассмотрели как использовать темы и стили на уровне кода, на примере кастомной view. В этой статье давайте разберем несколько способов стилизации стандартного ui элемента, а в частности SwitchCompat.
Содержание
Введение
Не всегда оформление по умолчанию стандартного UI элемента устраивает дизайнера. Давайте разберем, как поменять внешний вид элемента на примере SwitchCompat.
Для решения задачи нам нужно:
- Создать свой стиль для SwitchCompat.
- Каким-то образом задать этот стиль SwitchCompat.
Назначить стиль SwitchCompat можно несколькими способами, например:
- Указывать для каждой view в верстке экранов через атрибут style.
- Создать тему с переопределенным атрибутом switchStyle и назначить эту тему в манифесте для всего приложения или конкретной активити. Это изменит внешний вид view для всего приложения/активити.
- Тему также можно установить программно, в коде активити. При необходимости ее можно менять «на лету».
Новый стиль для SwitchCompat
В ресурсах создадим новый стиль MySwitchStyle, наследуем оформление от Widget.AppCompat.CompoundButton.Switch, задав parent. Можно и не наследовать, но тогда придется указать все значения, даже которые мы не планируем менять.
Чтобы что-то изменить, надо переопределить требуемые атрибуты. Атрибуты можно посмотреть в документации.
В документации видим несколько атрибутов. Они указаны в виде, как если бы мы обращались к ним в коде (например, вот так R.styleable.SwitchCompat_android_thumb). Я расшифрую только часть из них, чтобы не было сомнений. Назначение остальных несложно понять из документации.
В коде | В xml |
SwitchCompat_android_thumb | android:thumb |
SwitchCompat_thumbTint | thumbTint |
SwitchCompat_track | track |
SwitchCompat_trackTint | trackTint |
- android:thumb — ресурс для подвижной части SwitchCompat
- track — ресурс для неподвижной части SwitchCompat
- thumbTint — позволяет окрашивать подвижную часть в нужные цвета в зависимости от состояния SwitchCompat
- trackTint — позволяет окрашивать неподвижную часть в нужные цвета в зависимости от состояния SwitchCompat
В качестве примера изменим цвет thumb (кружочка) — пусть во включенном состоянии он будет оранжевым, в выключенном — зеленым. Некрасиво, но наглядно.
Нам понадобится селектор в папке color наших ресурсов. Файл selector_switch_thumb.xml
Теперь зададим атрибут thumbTint в нашем стиле.
Теперь все SwitchCompat, получившие каким-то образом стиль MySwitchStyle, будут выглядеть по-новому.
Стиль в верстке
Самый тривиальный и негибкий способ.
- Стиль применяется при inflate ресурса layout.
- Повлиять программно мы никак не можем.
- Указывать каждый раз в верстке неудобно. И можем забыть.
Стиль в теме. Тема назначается через Manifest
Создаем тему AppTheme и задаем значение атрибуту switchStyle. Значением является наш стиль MySwitchStyle.
Тема может быть указана в манифесте для всего приложения
Или для конкретной активити
Теперь все SwitchCompat будут иметь новый внешний вид. Без изменения в верстке.
- Плюсы — Можем менять внешний вид для всего приложения сразу.
- Минусы — налету менять не получится.
Стиль в теме. Тема назначается программно
Для того, чтобы установить тему для активити программно, нужно вызвать метод активити setTheme(themeResId).
Давайте менять тему активити в зависимости от состояния Switch.
- Устанавливаем тему программно, вызвав setTheme. Метод надо вызывать до super.onCreate(savedInstanceState). В onCreate у нас происходит инициализация фрагментов (когда они есть).
- Задаем начальное состояние Switch в зависимости от темы.
- Устанавливаем листенер, который при изменении Switch меняет тему в настройках и перезапускает активити через метод активити recreate().
Результат
Другие View
Чтобы переопределить стиль для SwitсhView для всего приложения, мы переопределили значение атрибута switchStyle, можно догадаться, что такие атрибуты есть и для других View.
- editTextStyle
- checkboxStyle
- radioButtonStyle
Как их искать? Я просто смотрю исходники, через Android Studio.
Заходим в тему, зажимаем ctrl, кликаем на родителе нашей темы. Смотрим, как описывают тему ребята из Google. Смотрим, какой атрибут определяется и от какого стиля можно отнаследоваться. Пользуемся.
Кусок из темы Base.V7.Theme.AppCompat.Light.
Ресурсы
Статья не претендует на полный справочник. Код умышленно сокращен. Я ставил задачу дать общее понимание — как это работает и зачем это нужно. Дальше все легко ищется в документации и в стандартных ресурсах.
Источник
romannurik / AndroidManifest.xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
manifest . > |
. |
Make sure your app (or individual activity) uses the |
theme with the custom attribute defined. —> |
application android : theme = » @style/AppTheme » . > |
. |
application > |
manifest > |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
public class MyActivity extends Activity < |
protected void onCreate ( Bundle savedInstanceState ) < |
super . onCreate(savedInstanceState); |
. |
// Pass in the theme attribute that’ll resolve to the |
// desired button style resource. The current theme |
// must have a value set for this attribute. |
Button myButton = new Button ( this , null , R . attr . myButtonStyle); |
myButton . setText( » Hello world » ); |
ViewGroup containerView = ( ViewGroup ) findViewById( R . id . container); |
containerView . addView(myButton); |
> |
> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
The convention is to put the And TextView initialization does: But it doesn’t recognize fontFamily attribute :S Is it a normal behaviour? This comment has been minimized.Copy link Quote reply jrub commented Jun 24, 2015Very useful indeed, thanks Roman. This should definitely be included into the official documentation for Themes & Styles (http://developer.android.com/guide/topics/ui/themes.html) This comment has been minimized.Copy link Quote reply ursusursus commented Feb 19, 2016For me this does not apply layout params like layout_width, layout_height when I have them in my style. Only default wrap_content LayoutParams gets created in both dimensions Источник Android: set view style programmaticallyPosted by: admin November 16, 2017 Leave a comment How to set style attribute programmatically? Technically you can apply styles programmatically, with custom views anyway: The one argument constructor is the one used when you instantiate views programmatically. So chain this constructor to the super that takes a style parameter. Or as @Dori pointed out simply: You cannot set a view’s style programmatically yet, but you may find this thread useful. Update: At the time of answering this question (mid 2012, API level 14-15), setting the view programmatically was not an option (even though there were some non-trivial workarounds)whereas this has been made possible after the more recent API releases. See @Blundell’s answer for details. What worked for me:
You can apply a style to your activity by doing: or Android default: in your activity, before setContentView() . Non of the provided answers are correct. You CAN set style programatically. Long answer. 1) Create a style in your styles.xml file Do not forget to define your custom attributes in attrs.xml file My attrsl.xml file: Notice you can use any name for your styleable (my CustomWidget) Now lets set the style to the widget Programatically And finally StyleLoader class implementation I used views defined in XML in my composite ViewGroup, inflated them added to Viewgroup. This way I cannot dynamically change style but I can make some style customizations. My composite: and my view in xml where i can assign styles: You can create the xml containing the layout with the desired style and then change the background resource of your view, like this. Related Postsandroid – How do I display a CalendarView in an AlertDialog?Questions: I’m trying to display the CalendarView in an Alert Dialog, but all that shows up is the month/year and the days of the week. These are the contents of the layout file: How do I convert a PSD design to Android xml?Questions: Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers. Want to improve this question? Update the question so it’s on-topic for Stack Over. Источник Android: установить стиль просмотра программноКак установить style атрибут программно? Технически вы можете применять стили программно, в любом случае с пользовательскими представлениями: Конструктор с одним аргументом используется при создании экземпляров представлений программным способом. Так что цепочка этого конструктора супер, который принимает параметр стиля. Или, как @Dori указал просто: Что сработало для меня:
Обновление : во время ответа на этот вопрос (середина 2012 года, уровень API 14-15), программная настройка представления не была возможной (даже если были некоторые нетривиальные обходные пути), хотя это стало возможным после более позднего API релизы. Смотрите ответ @ Blundell для деталей. СТАРЫЙ ответ: Вы не можете установить стиль представления программно, но вы можете найти эту тему полезной. Для новой кнопки / TextView: Для существующего экземпляра: Для изображения или макетов: Если вы хотите продолжить использовать XML (что не позволяет сделать принятый ответ) и установить стиль после создания представления, вы можете использовать парижскую библиотеку, которая поддерживает подмножество всех доступных атрибутов. Поскольку вы надуваете свое представление из XML, вам нужно указать идентификатор в макете: Затем, когда вам нужно изменить стиль программно, после того, как макет был раздут: Отказ от ответственности: я первый автор указанной библиотеки. Вы можете применить стиль к своей деятельности, выполнив: или Android по умолчанию: в вашей деятельности, до setContentView() . Ни один из приведенных ответов не является правильным. Вы можете установить стиль программно. Длинный ответ Вот мой фрагмент, чтобы программно установить пользовательский стиль на ваш взгляд: 1) Создайте стиль в вашем файле styles.xml Не забудьте указать свои пользовательские атрибуты в файле attrs.xml Мой файл attrsl.xml: Обратите внимание, что вы можете использовать любое имя для вашего стиля (мой CustomWidget) Теперь давайте установим стиль для виджета программно. Вот мой простой виджет: И, наконец, реализация класса StyleLoader Это довольно старый вопрос, но решение, которое сработало для меня сейчас, заключается в использовании 4-го параметра конструктора defStyleRes — если доступно .. на виду . для установки стиля Следующие работы для моих целей (kotlin): Это мой простой пример, ключом является ContextThemeWrapper обертка, без нее мой стиль не работает, и используется конструктор с тремя параметрами View. простой путь проходит через конструктор Я не предлагаю использовать ContextThemeWrapper, поскольку это делает это:
Что может привести к нежелательным результатам в вашем приложении. Вместо этого я предлагаю новую библиотеку «Париж» для этого от инженеров Airbnb:
Но после некоторого времени использования я обнаружил, что он на самом деле довольно ограничен, и я перестал его использовать, потому что он не поддерживает много свойств, которые мне нужны, из коробки, поэтому нужно проверить и решить как всегда. Источник How to programmatically setting style attribute in a viewI’m getting a view from the XML with the code below: I would like to set a «style» for the button how can I do that in java since a want to use several style for each button I will use. Generally you can’t change styles programmatically; you can set the look of a screen, or part of a layout, or individual button in your XML layout using themes or styles. Themes can, however, be applied programmatically. There is also such a thing as a StateListDrawable which lets you define different drawables for each state the your Button can be in, whether focused, selected, pressed, disabled and so on. For example, to get your button to change colour when it’s pressed, you could define an XML file called res/drawable/my_button.xml directory like this: You can then apply this selector to a Button by setting the property android:background=»@drawable/my_button» . First of all, you don’t need to use a layout inflater to create a simple Button. You can just use: If you want to style the button you have 2 choices: the simplest one is to just specify all the elements in code, like many of the other answers suggest: The other option is to define the style in XML, and apply it to the button. In the general case, you can use a ContextThemeWrapper for this: To change the text-related attributes on a TextView (or its subclasses like Button) there is a special method: This last one cannot be used to change all attributes; for example to change padding you need to use a ContextThemeWrapper . But for text color, size, etc. you can use setTextAppearance . Yes, you can use for example in a button The answer by @Dayerman and @h_rules is right. To give an elaborated example with code, In drawable folder, create an xml file called button_disabled.xml This will set the button’s property to disabled and sets the color to silver. [The color is defined in color.xml as: For anyone looking for a Material answer see this SO post: Coloring Buttons in Android with Material Design and AppCompat I used a combination of this answer to set the default text color of the button to white for my button: https://stackoverflow.com/a/32238489/3075340 Then this answer https://stackoverflow.com/a/34355919/3075340 to programmatically set the background color. The code for that is: your_colored_button can be just a regular Button or a AppCompat button if you wish — I tested the above code with both types of buttons and it works. EDIT: I found that pre-lollipop devices do not work with the above code. See this post on how to add support for pre-lollipop devices: https://stackoverflow.com/a/30277424/3075340 Basically do this: At runtime, you know what style you want your button to have. So beforehand, in xml in the layout folder, you can have all ready to go buttons with the styles you need. So in the layout folder, you might have a file named: button_style_1.xml. The contents of that file might look like: If you are working with fragments, then in onCreateView you inflate that button, like: where container is the ViewGroup container associated with the onCreateView method you override when creating your fragment. Need two more such buttons? You create them like this: You can customize those buttons: Then you add your customized, stylized buttons to the layout container you also inflated in the onCreateView method: And that’s how you can dynamically work with stylized buttons. You can do style attributes like so: If you are using the Support library, you could simply use for TextViews and Buttons. There are similar classes for the rest of Views 🙂 I faced the same problem recently. here is how i solved it.
If some one needs colors Buttons or RadioButton or CheckBox then Simply use AppCompatButton or AppCompatRadioButton or AppCompatCheckBox With simple codes like : And for Radio Button And for Check Box I made a helper interface for this using the holder pattern. Now for every style you want to use pragmatically just implement the interface, for example: Declare a stylable in your attrs.xml , the styleable for this example is: Here is the style declared in styles.xml : And finally the implementation of the style holder: I found this very helpful as it can be easily reused and keeps the code clean and verbose, i would recommend using this only as a local variable so we can allow the garbage collector to do its job once we’re done with setting all the styles. Источник |