Set button style programmatically

So, I programmatically create new buttons and add them to LinearLayout, however I want to initialize these buttons with a predefined style. I spent some time finding a solution and tried out the answers, but I still can't get it to work.

When I add a new button to the layout, it should look like buttons (at the top) in this image .

I tried to create an xml file in res / values ​​/ and initialize the button with new Button(context, null, R.style.ChoiceButton), but this will not work, getting this to happen .

I also tried a workaround for creating a new xml layout for the button and with (Button)getLayoutInflater().inflate(R.layout.choice_buttton_layout, null), but this also did not work, as a result of this (two buttons to show lack of stock) .

RES / value / choice_button.xml

<resources>
    <style name="ChoiceButton">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_gravity">center_horizontal</item>
        <item name="android:layout_marginBottom">7dp</item>
        <item name="android:minWidth">250dp</item>
        <item name="android:background">#ff27ae60</item>
        <item name="android:textColor">#ffffffff</item>
        <item name="android:enabled">true</item>
    </style>
</resources>

Fragment from Main.java

public void btnAdd_click(View view) {
        Button newBtn = new Button(getApplicationContext(), null, R.style.ChoiceButton);
        newBtn.setText("new button");
        newBtn.setId(Util.generateViewId());

        LinearLayout layout = (LinearLayout)findViewById(R.id.layoutTop);
        layout.addView(newBtn);
    }

activity_main.xml

A bit longer to insert here.

Is there something I am missing? Is it possible?

+4
source share
1 answer

Ok @ kin3tik, I found an old application that I made with some custom button. See how it looks:

enter image description here

there is my xml for one button:

<Button
                android:id="@+id/num1"
                android:layout_width="110dp"
                android:layout_height="100dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:text="@string/num1"
                android:textSize="20sp" />

I created a .xml file in my available custombutton.xml folder:

<shape xmlns:android="http://schemas.android.com/apk/res/android">

<solid android:color="@color/bleuperso"/> // you can put #XXXXXX for the color you want 
<corners android:radius="4dp"/>

And I just put the style in java:

Bfrancois.setBackgroundResource(R.drawable.custombutton);

With this, you can find yourself;)

+1
source