4
votes

So I'm programmatically creating new buttons and adding them to a LinearLayout, however I want to initialize these buttons with a predefined style. I've spent some time searching for a solution and trying out answers, but I still can't seem to get it to work.

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

I've tried creating an xml file in res/values/ and initializing a button with new Button(context, null, R.style.ChoiceButton), but it doesn't work resulting in this happening.

I've also tried the workaround of creating a new layout xml for the button and using (Button)getLayoutInflater().inflate(R.layout.choice_buttton_layout, null), but that also didn't work, resulting in this (two buttons to show lack of margin).

res/values/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>

Snippet 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 long to paste in here.

Is there just something I'm missing? Is this even possible?

1

1 Answers

1
votes

Ok @kin3tik, I found an old application I made with some custom button.. see what it looks like :

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 file .xml in my drawable folder custombutton.xml:

<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 should be able to find yourself ;)