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
Is there just something I'm missing? Is this even possible?