Android - adding a view programmatically ignores some style attributes

I add a button programmatically to my existing Android view when a user removes another button. It works in terms of functionality, but some style data seems to be ignored.

I add a button, having a separate layout containing only the button, with the style value pre-populated.

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

Using getLayoutInflater, I can 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 a values โ€‹โ€‹directory that sets color, text, etc. for @style/FileStorageDeleteButton, most of which are used by the button when adding it. But for some reason, the four margin attributes are layout_belowignored.

I do not get errors in LogCat when this button appears, as if the style just doesn't apply. If I include a button manually in XML for this layout, it successfully uses all the styles.

Any help is greatly appreciated.

+5
source share
1 answer

You need to pass the layout parameters when invoked addView(), since the layout parameters are not of the same view, they are always accepted in the context of the surrounding view . There are options addView()that take an argument LayoutParams.

EDIT Add more details.

You have to create a set LinearLayout.LayoutParamsand set your fields there, then pass this toaddView()

layout_below LinearLayout ( RelativeLayout. addView(buttonDelete, 1), , .

+3

All Articles