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.