Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Adding a View Programatically Ignores Some Style Attributes

I'm adding a button programatically into my existing Android view, when the user taps another button. It's working in terms of functionality, but some of the style information seems to be being ignored.

I'm adding the button by having a separate layout containing just the button, with the style value pre-filled.

<Button xmlns:android="http://schemas.android.com/apk/res/android" style="@style/FileStorageDeleteButton"></Button>

By using getLayoutInflater, I'm then able to add this button to the layout.

buttonDelete = (Button) getLayoutInflater().inflate(R.layout.pete_button_filedelete, null);

LinearLayout layout = (LinearLayout)findViewById(R.id.layoutFileStorage);

layout.addView(buttonDelete, 1);

I have an XML file in the values directory which sets the colour, text etc for @style/FileStorageDeleteButton, most of which are being used by the button when it's added. But for some reason the four margin attributes and layout_below are being ignored.

I'm getting no errors in the LogCat when this button appears, it's as though the styling simply isn't being applied. If I include the button manually in the XML for that layout, it uses all of the styles successfully.

Any help much appreciated.

like image 489
Pete G Avatar asked Oct 21 '22 14:10

Pete G


1 Answers

You need to pass the layout parameters when you call addView() because layout parameters are not relevant for a single view, they are always taken in context of the surrounding view. There are variants of addView() that take a LayoutParams argument.

EDIT Add more details

You should create a set of LinearLayout.LayoutParams and set your margins in there, then pass that to addView()

layout_below is ignored for a LinearLayout anyway (that attribute is only relevant for a RelativeLayout. When you call addView(buttonDelete, 1) you are telling it where to put the view in the linear layout.

like image 142
David Wasser Avatar answered Oct 29 '22 18:10

David Wasser