Android studio set style programmatically

How do I apply a style programmatically?

I have a styles called Red and Green and I have an if statment to find out which to apply, but I don’t know the code to actually apply a style from the java.

4 Answers 4

There is no one line solution to this problem, but this worked for my use case. The problem is, the ‘View(context, attrs, defStyle)’ constructor does not refer to an actual style, it wants an attribute. So, we will:

  1. Define an attribute
  2. Create a style that you want to use
  3. Apply a style for that attribute on our theme
  4. Create new instances of our view with that attribute

In ‘res/values/attrs.xml’, define a new attribute:

In res/values/styles.xml’ I’m going to create the style I want to use on my custom TextView

In ‘res/values/themes.xml’ or ‘res/values/styles.xml’, modify the theme for your application / activity and add the following style:

Finally, in your custom TextView, you can now use the constructor with the attribute and it will receive your style. Here, instead of always

With all of these components, you can now do an if/else statement to generate new views at runtime with the style you prefer

It’s worth noting that I repeatedly used customTextView in different variants and different places, but it is in no way required that the name of the view match the style or the attribute or anything. Also, this technique should work with any custom view, not just TextViews.

Источник

Android: установка стиля просмотра программно

Как настроить style атрибут программно?

10 ответов

технически вы можете применять стили программно, с пользовательскими представлениями в любом случае:

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

поэтому свяжите этот конструктор с Супер, который принимает параметр стиля.

или, как @Dori указал просто:

что сработало для меня:

  • используйте конструктор 3-arguments (не будет работать без этого)

вы не может установите стиль представления программно, но вы можете найти этой теме полезное.

обновление: на момент ответа на этот вопрос (середина 2012 года, уровень API 14-15) установка представления программно не была опцией (хотя были некоторые нетривиальные обходные пути), тогда как это стало возможным после более поздних выпусков API. Подробнее см. В ответе @Blundell.

вы можете применить стиль к своей деятельности, выполнив:

или Android по умолчанию:

в вашей деятельности, перед setContentView() .

для новой кнопки / TextView:

для существующего экземпляра:

для изображения или макеты:

не предоставил ответы верны.

вы можете установить стиль программно.

длинный ответ. Вот мой фрагмент, чтобы установить пользовательский стиль программно для вашего представления:

1) Создайте стиль в ваших стилях.xml-файл

не забудьте определить свои пользовательские атрибуты в attrs.xml-файл

обратите внимание, что вы можете использовать любое имя для вашего styleable (my CustomWidget)

теперь позволяет установить стиль виджета программно Вот мой простой виджет:

и, наконец, реализация класса StyleLoader

Если вы хотите продолжить использовать XML (что не позволяет сделать принятый ответ) и установить стиль после создания представления, вы можете использовать библиотеку Paris, которая поддерживает подмножество всех доступных атрибутов.

поскольку вы раздуваете свое представление из XML, вам нужно будет указать идентификатор в макете:

затем, когда вам нужно изменить стиль программно, после того, как макет был завышен:

Читайте также:  Андроид вай фай сохранено

отказ от ответственности: я автор библиотеки.

я использовал представления, определенные в XML в моей составной ViewGroup, надул их, добавленные в Viewgroup. Таким образом, я не могу динамически изменять стиль, но я могу сделать некоторые настройки стиля. Мой композит:

и мой вид в xml, где я могу назначить стили:

Это мой простой пример, ключ ContextThemeWrapper wrapper, без него мой стиль не работает и использует конструктор трех параметров представления.

вы можете создать xml, содержащий макет с желаемым стилем, а затем изменить фоновый ресурс вашего представления, например этой.

Источник

Android — set TextView TextStyle programmatically?

Is there a way to set the textStyle attribute of a TextView programmatically? There doesn’t appear to be a setTextStyle() method.

To be clear, I am not talking about View / Widget styles! I am talking about the following:

11 Answers 11

setTypeface is the Attribute textStyle.

As Shankar V added, to preserve the previously set typeface attributes you can use:

Let’s say you have a style called RedHUGEText on your values/styles.xml:

Just create your TextView as usual in the XML layout/your_layout.xml file, let’s say:

And in the java code of your Activity you do this:

It worked for me! And it applied color, size, gravity, etc. I’ve used it on handsets and tablets with Android API Levels from 8 to 17 with no problems. Note that as of Android 23, that method has been deprecated. The context argument has been dropped, so the last line would need to be:

To support all API levels use androidX TextViewCompat

Remember. this is useful only if the style of the text really depends on a condition on your Java logic or you are building the UI «on the fly» with code. if it doesn’t, it is better to just do:

You can always have it your way!

or if u want through xml

• Kotlin Version

To retain current font in addition to text style:

This question is asked in a lot of places in a lot of different ways. I originally answered it here but I feel it’s relevant in this thread as well (since i ended up here when I was searching for an answer).

There is no one line solution to this problem, but this worked for my use case. The problem is, the ‘View(context, attrs, defStyle)’ constructor does not refer to an actual style, it wants an attribute. So, we will:

  1. Define an attribute
  2. Create a style that you want to use
  3. Apply a style for that attribute on our theme
  4. Create new instances of our view with that attribute

In ‘res/values/attrs.xml’, define a new attribute:

In res/values/styles.xml’ I’m going to create the style I want to use on my custom TextView

In ‘res/values/themes.xml’ or ‘res/values/styles.xml’, modify the theme for your application / activity and add the following style:

Finally, in your custom TextView, you can now use the constructor with the attribute and it will receive your style

It’s worth noting that I repeatedly used customTextView in different variants and different places, but it is in no way required that the name of the view match the style or the attribute or anything. Also, this technique should work with any custom view, not just TextViews.

Источник

Android: set view style programmatically

How to set style attribute programmatically?

15 Answers 15

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:

What worked for me:

  • Use a ContextThemeWrapper
  • Use the 3-arguments constructor (won’t work without this)

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.

OLD Answer:

You cannot set a view’s style programmatically yet, but you may find this thread useful.

For a new Button/TextView:

For an existing instance:

For Image or layouts:

This is quite old question but solution that worked for me now is to use 4th parameter of constructor defStyleRes — if available.. on view. to set style

Following works for my purposes (kotlin):

If you’d like to continue using XML (which the accepted answer doesn’t let you do) and set the style after the view has been created you may be able to use the Paris library which supports a subset of all available attributes.

Since you’re inflating your view from XML you’d need to specify an id in the layout:

Then when you need to change the style programmatically, after the layout has been inflated:

Disclaimer: I’m the original author of said library.

You can apply a style to your activity by doing:

or Android default:

in your activity, before setContentView() .

This is my simple example, the key is the ContextThemeWrapper wrapper, without it, my style does not work, and using the three parameters constructor of the View.

Non of the provided answers are correct.

You CAN set style programatically.

Long answer. Here’s my snippet to set custom defined style programatically to your view:

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 Here’s My simple widget:

And finally StyleLoader class implementation

the simple way is passing through constructor

I don’t propose to use ContextThemeWrapper as it do this:

The specified theme will be applied on top of the base context’s theme.

What can make unwanted results in your application. Instead I propose new library «paris» for this from engineers at Airbnb:

Define and apply styles to Android views programmatically.

But after some time of using it I found out it’s actually quite limited and I stopped using it because it does not support a lot of properties i need out off the box, so one have to check out and decide as always.

Источник

How to programmatically set style attribute in a view

I’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.

11 Answers 11

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:

Or, if you need to support devices pre API-23 (Android 6.0)

This method 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 .

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» .

Yes, you can use for example in a button

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 🙂

Depending on what style attributes you’d like to change you may be able to use the Paris library:

Many attributes like background, padding, textSize, textColor, etc. are supported.

Disclaimer: I authored the library.

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.

Источник

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