Adam Varhegyi Adam Varhegyi - 5 months ago 71
Android Question

How to set layout_gravity programmatically?

My question is simple,

How to set my buttons layout_gravity programmatically?

I found this on internet, but it 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);


Any solution?

Answer
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.TOP;

button.setLayoutParams(params);

For gravity values and how to set gravity check Gravity

Comments