toom
toom

Reputation: 13316

LinearLayout setMargins programmatically has not effect

Please have a look at the following code:

        LinearLayout ll1 = new LinearLayout(context);
        ll1.setBackgroundColor(Color.BLUE);
        ll1.setOrientation(LinearLayout.VERTICAL);
        LinearLayout.LayoutParams ll1LayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        ll1LayoutParams.setMargins(100, 0, 100, 0);
        ll1.setLayoutParams(ll1LayoutParams);
        ...
        // parentLayout is FrameLayout
        parentLayout.addView(ll1, ll1LayoutParams);

Why doesn't it work?

Upvotes: 1

Views: 146

Answers (1)

Raghu Teja
Raghu Teja

Reputation: 225

Change

LinearLayout.LayoutParams ll1LayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

to

FrameLayout.LayoutParams ll1LayoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

When assigning layout params to a child, you must assign the LayoutParams class of its parent and not the view. Since here your parent view is a FrameLayout, you have to use FrameLayout.LayoutParams.

Upvotes: 2

Related Questions