How would I set layout_gravity programatically for buttons?
I am implementing it , but its simply throws me a NullPointer exception:
Button MyButton = new Button(this);
LinearLayout.LayoutParams lllp=(LinearLayout.LayoutParams)MyButton.getLayoutParams();
lllp.gravity=Gravity.RIGHT;
MyButton.setLayoutParams(lllp);
MyLinearLayout.addView(MyButton)
Aryan Kumar
27-Jun-2023Sure, here is how to set layout gravity for buttons programmatically:
Code snippet
In this code, we first get the button from the layout using the
findViewById()
method. Then, we set the gravity of the button using thesetGravity()
method. ThesetGravity()
method takes two arguments: the first argument is the horizontal gravity, and the second argument is the vertical gravity. In this case, we are setting the horizontal gravity to LEFT and the vertical gravity to TOP.The
Gravity
class defines a number of constants that you can use to specify the gravity of a view. For example, theGravity.TOP
constant specifies that the view should be placed at the top of its parent. TheGravity.LEFT
constant specifies that the view should be placed at the left of its parent.You can also combine the horizontal and vertical gravity constants using the bitwise OR operator (
|
). For example, the following code sets the gravity of the button to the top-left corner:Code snippet
Anonymous User
18-Jan-2016