Adam Varhegyi Adam Varhegyi - 2 years ago 191
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();


Any solution?

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


For gravity values and how to set gravity check Gravity

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download