0

I have added a Button to a view in java code. Basically I want to add the xml

android:layout_gravity="center_horizontal"

to the Button but do this in Java code, how is this done?

jax
  • 37,735
  • 57
  • 182
  • 278
  • 2
    duplicate of http://stackoverflow.com/questions/2945315/java-method-for-androidlayout-gravity – Key Jul 02 '10 at 08:22
  • That is for a FrameLayout and I already tired it before posting, it does not work. – jax Jul 02 '10 at 09:16
  • 1
    Incedendly this is what I tried: myButton.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL)); – jax Jul 02 '10 at 09:21
  • Update the question instead of posting ckde in comments – Moog Nov 24 '12 at 22:09

2 Answers2

3

use following method on your layout or on any view.

layout.setGravity(Gravity.CENTER_HORIZONTAL);
kaushal trivedi
  • 3,405
  • 3
  • 29
  • 47
1
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams
        ( (int) LayoutParams.WRAP_CONTENT, (int) LayoutParams.WRAP_CONTENT);

params.addRule(RelativeLayout.CENTER_HORIZONTAL);

button.setLayoutParams(params);
Balaji
  • 2,024
  • 17
  • 13