How to programmatically set style attribute in a view

I'm getting a view from the XML with the code below:

Button view = (Button) LayoutInflater.from(this).inflate(R.layout.section_button, null);

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.

Asked by: Emma217 | Posted: 24-01-2022

Answer 1

First of all, you don't need to use a layout inflater to create a simple Button. You can just use:

button = new Button(context);

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:

button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);

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:

ContextThemeWrapper newContext = new ContextThemeWrapper(baseContext,;
button = new Button(newContext);

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.

Answered by: Elise436 | Posted: 25-02-2022

Answer 2

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:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="">
    android:drawable="@drawable/btn_pressed" />
    android:drawable="@drawable/btn_normal" />

You can then apply this selector to a Button by setting the property android:background="@drawable/my_button".

Answered by: Brooke703 | Posted: 25-02-2022

Answer 3

Yes, you can use for example in a button

Button b = new Button(this);

Answered by: Leonardo235 | Posted: 25-02-2022

Answer 4

You can do style attributes like so:

Button myButton = new Button(this, null,android.R.attr.buttonBarButtonStyle);

in place of:



Answered by: Dexter262 | Posted: 25-02-2022

Answer 5

If you are using the Support library, you could simply use


for TextViews and Buttons. There are similar classes for the rest of Views :-)

Answered by: Adelaide103 | Posted: 25-02-2022

Answer 6

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

Button view = (Button) LayoutInflater.from(this).inflate(R.layout.section_button, null);;

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

Disclaimer: I authored the library.

Answered by: Miller753 | Posted: 25-02-2022

Answer 7

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

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android=""
android:shape="rectangle" android:padding="10dp">   
 <solid android:color="@color/silver"/>

Then in Java,

((Button) findViewById(;
((Button) findViewById(;

This will set the button's property to disabled and sets the color to silver.

[The color is defined in color.xml as:


    <color name="silver">#C0C0C0</color>


Answered by: Daryl372 | Posted: 25-02-2022

Answer 8

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:

Then this answer 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:

Basically do this:

Button b = (Button) findViewById(;
ColorStateList c = ContextCompat.getColorStateList(mContext, R.color.your_custom_color;
Drawable d = b.getBackground();
if (b instanceof AppCompatButton) {
    // appcompat button replaces tint of its drawable background
    // Lollipop button replaces tint of its drawable background
    // however it is not equal to d.setTintList(c)
} else {
    // this should only happen if 
    // * manually creating a Button instead of AppCompatButton
    // * LayoutInflater did not translate a Button to AppCompatButton
    d = DrawableCompat.wrap(d);
    DrawableCompat.setTintList(d, c);

Answered by: Kevin529 | Posted: 25-02-2022

Answer 9

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:

<?xml version="1.0" encoding="utf-8"?>
    style="@style/FirstStyle" />

If you are working with fragments, then in onCreateView you inflate that button, like:

Button firstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);

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:

Button secondFirstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);
Button thirdFirstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);

You can customize those buttons:

secondFirstStyleBtn.setText("My Second");
thirdFirstStyleBtn.setText("My Third");

Then you add your customized, stylized buttons to the layout container you also inflated in the onCreateView method:

_stylizedButtonsContainer = (LinearLayout) rootView.findViewById(;


And that's how you can dynamically work with stylized buttons.

Answered by: Byron657 | Posted: 25-02-2022

Answer 10

I made a helper interface for this using the holder pattern.

public interface StyleHolder<V extends View> {
    void applyStyle(V view);

Now for every style you want to use pragmatically just implement the interface, for example:

public class ButtonStyleHolder implements StyleHolder<Button> {

    private final Drawable background;
    private final ColorStateList textColor;
    private final int textSize;

    public ButtonStyleHolder(Context context) {
        TypedArray ta = context.obtainStyledAttributes(, R.styleable.ButtonStyleHolder);

        Resources resources = context.getResources();

        background = ta.getDrawable(ta.getIndex(R.styleable.ButtonStyleHolder_android_background));

        textColor = ta.getColorStateList(ta.getIndex(R.styleable.ButtonStyleHolder_android_textColor));

        textSize = ta.getDimensionPixelSize(

        // Don't forget to recycle!

    public void applyStyle(Button btn) {
        btn.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);

Declare a stylable in your attrs.xml, the styleable for this example is:

<declare-styleable name="ButtonStyleHolder">
    <attr name="android:background" />
    <attr name="android:textSize" />
    <attr name="android:textColor" />

Here is the style declared in styles.xml:

<style name="button">
    <item name="android:background">@drawable/button</item>
    <item name="android:textColor">@color/light_text_color</item>
    <item name="android:textSize">@dimen/standard_text_size</item>

And finally the implementation of the style holder:

Button btn = new Button(context);    
StyleHolder<Button> styleHolder = new ButtonStyleHolder(context);

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.

Answered by: Agata411 | Posted: 25-02-2022

Answer 11

I faced the same problem recently. here is how i solved it.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""

    <!-- This is the special two colors background START , after this LinearLayout, you can add all view that have it for main background-->



        android:background="#0000FF" />

        android:background="#F000F0" />
    <!-- This is the special two colors background END-->

    android:text="This Text is centered with a special backgound,
    You can add as much elements as you want as child of this RelativeLayout"
    android:textSize="20sp" />
  • I used a LinearLayout with android:weightSum="2"
  • I gave to the two child elements android:layout_weight="1" (I gave each 50% of the parent space(width & height))
  • And finally, i gave the two child element different background colors to have the final effect.

Thanks !

Answered by: Miller400 | Posted: 25-02-2022

Similar questions

android - How to programmatically override XML height attribute?

I have an Activity with linear layout. It has two Views - one Button and one custom View beneath. I want to be able to set the custom one's height programmatically (it will be calculated during the startup from an image drawn onto it). And I want the button above it to fill the remaining space. How to achieve this? So far I have this XML code: &lt;LinearLayout xmlns:android="

android - Programmatically change one attribute on custom style

I am creating several textviews that all use the same style. I am attempting to use a SeekBar to update the textsize within the Style so it applies to all textviews with a minimal amount of code. I know I can use a SeekBar to set the textsize of the textviews individually but that seems like a lot of work. The problem is that everywhere I look all I find is that you cannot change the style. Is there any other work around b...

java - How to set a custom attribute on a view programmatically

I'm trying to set a custom attribute to my view programmatically, to set a validation state. First, I created this layout for a text field: &lt;layer-list xmlns:android=""&gt; &lt;item&gt; &lt;shape&gt; &lt;solid android:color="@android:color/transparent" /&gt; &lt;/shape&gt; &lt;/item&gt; &lt;item android:right="1dp" android:left="1dp"&gt;...

java - How to get a value of color attribute programmatically

When I use resolveAttribute() to find out a color value of ?attr/colorControlNormal, I got 236: TypedValue typedValue = new TypedValue(); getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true); int color =; // 236 But when I use an XML layout with the following TextView element: &lt...

java - How to change style attribute value in programmatically?

I have button and I set style from xml now on click of button I want to change style like style="@style/ButtonNotSelected" Place to style="@style/ButtonSelected" programmatically.. Please help..!!!

java - How to change specific XML attribute of custom UI element programmatically in android

I am using a custom UI component in my project which has it's own few attributes. I want to change a specific one using a function when it is clicked. I don't know how to access it though, I am fairly new in this department. &lt;com.chinodev.androidneomorphframelayout.NeomorphFrameLayout android:id="@+id/btnsystem" android:layout_width="wrap_content" ...

java - How to set custom theme attribute programmatically in Android 10

It is easy to change theme attributes in styles.xml, and to define new custom theme attributes in attrs.xml. But how to do it in java code? After calling setTheme in Activity, how to change or define attribute programmatically? @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstan...

Android Theme Style find and read correct attribute programmatically

I'm sure there is somewhere an correct answer to what I need, but i can't find it :( I need to read programmatically attributes from style from theme... Here some simple code to make it more understandable. //Custom attributes &lt;declare-styleable name=&quot;Style_lib&quot;&gt; &lt;attr name=&quot;layoutElementStyle&quot; format=&quot;reference&quot;/&gt; &lt;/declare-styleable&gt; ...

java - how to set value for attribute programmatically

&lt;declare-styleable name=&quot;MyColorsStyles&quot; &gt; &lt;attr name=&quot;RedColor&quot; format=&quot;color&quot; /&gt; &lt;/declare-styleable&gt; &lt;style name=&quot;AppTheme&quot; parent=&quot;Theme.AppCompat.Light.NoActionBar&quot;&gt; &lt;item name=&quot;RedColor&quot;&gt;#D32127&lt;/item&gt; &lt;/style&gt; this is how to set the RedColor to each theme. but the question i...

java - How to set attribute programmatically

I have an attribute &lt;attr name=&quot;ColorMain&quot; format=&quot;reference|color&quot; /&gt; If I need to set it as colors in the xml file then I write the following android:textColor=&quot;?attr/ColorText&quot; How do I do this programmatically? Tried doing like this but it doesn't work like that et_name.setTextColor(R.attr.ColorText...

user interface - Android: How to programmatically set dialog size?

I want do set size (in px) of dialog based on screen resolution, so I have to set dialog size programmatically during runtime. Dialog layout is defined in xml with all standard views, so it would be nice to have better way to set dialog size than override-in top view's onMeasure(...). (Android 1.5 SDK)

How to get the device's IMEI/ESN programmatically in android?

To identify each devices uniquely I would like to use the IMEI (or ESN number for CDMA devices). How to access this programmatically?

Get/pick an image from Android's built-in Gallery app programmatically

I am trying to open an image / picture in the Gallery built-in app from inside my application. I have a URI of the picture (the picture is located on the SD card). Do you have any suggestions?

Android: How to highlight EditText programmatically?

requestFocus() moves the cursor to the edit box, but does not highlight it. I want to highlight it like as if it was touched. How can I do this?

How to get device longitude and latitude programmatically in Android?

I don't know to how to get the latitude and longitude of device by programmatically? If you can provide some code snippet to get the latitude and longitude.

android - Capturing HOME intent programmatically

I need my activity to handle HOME button press with a receiver programmatically, but the event is not firing. I can, however, successfully register and capture this intent filter if I declare it in a manifest.xml activity section. Here's the code for the receiver that's not working: BroadcastReceiver br; br = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent...

android - Programmatically scrolling an EditText

I'm writing a simple caesar-encryption-activity. Two EditTexts on screen, one clear-text, one crypted. Here's an example for the crypted EditText - the cleartext one is similar. &lt;EditText android:layout_below="@id/Caesar_Label_CryptText" android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/Caesar_Text_CryptText" android:hint="Enter crypted text" ...

How to Programmatically Scroll Android WebView

I'm trying to programmatically scroll a WebView to the location of a particular element in the DOM tree. But so far I haven't been able to get the WebView to respond to scroll requests. I've tried calling JavaScript that uses window.scrollTo(...), but the WebView doesn't respond. On the Java side, I've tried calling the WebView.flingScroll(...) method. WebView will respond to flingScroll...

lockscreen - How to access programmatically what is displayed in an Android lock screen

Today I am looking for a way to mimic the behavior I know from my HTC Hero's lock screen: the calendar and alarm clock can put text &amp; drawables there to inform about an upcoming event or an expired alarm. The lock screen remains there in that it must be dragged down to dismiss the shown event and there might also be a Snooze button. But, first question: is this default Android stuff or HTC Sense specific only??...

android - Programmatically start / launch VPN connection

I am developing Enterprise applications that need to connect to servers behind the firewall. Can my app start VPN connection programmatically? On 2.0+ platforms, VPN is supported by the platform. Assuming user has already setup VPN parameters, can my app start the VPN connection? Suppose user has not setup any VPN parameters, can my app supply those parameters? and start VPN connection?

Still can't find your answer? Check out these communities...

Android Google Support | Android Community | Android Community (Facebook) | Android