0

I need to change the property android:layout_marginTop of a button programmatically. But the code below does not produce the same result as changing on the xml. I wonder if anyone can spot the issue, here's my button:

<Button
    android:id="@+id/cta_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="0dp"
    android:background="@color/cta_button_background"
    android:text="CTA"
    android:textColor="@color/cta_button_foreground"
    android:textSize="18sp"
    android:visibility="visible" />

now I need to change the "marginTop" programmatically based on some logic. Here is what I have tired but does not work properly.

    // Adjust button to float above the image
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);

    int marginTop = Pixel.convertPxToDp(someNumber);
    params.setMargins(0, marginTop, 0, 0);
    mCallToActionButton.setLayoutParams(params);
    mCallToActionButton.invalidate();

"mCallToActionButton" has a valid pointer to the button and 'someNumber' can be anything value.

I used this thread but the button is moving somewhere else, not just changing its topMargin

How to set a button's parameters programatically

thank you.

Community
  • 1
  • 1
gmmo
  • 2,577
  • 3
  • 30
  • 56

2 Answers2

1

This way works:

ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mCallToActionButton.getLayoutParams();
params.topMargin = Pixel.convertDpToPx(newImageMargin);
mCallToActionButton.setLayoutParams(params);
gmmo
  • 2,577
  • 3
  • 30
  • 56
  • Thank you very much for this solution, I've been looking for this for long time, all the others solutions didn't work but this one worked perfectly! – Simple Oct 08 '18 at 16:09
0

Try to set gravity to your LayoutParams

params.gravity = Gravity.CENTER_HORIZONTAL;
Cooper
  • 180
  • 5