403

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?

brainless
  • 5,698
  • 16
  • 59
  • 82
Adam Varhegyi
  • 11,307
  • 33
  • 124
  • 222

20 Answers20

623

Java

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

button.setLayoutParams(params);

Kotlin

val params = LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT,
    LinearLayout.LayoutParams.WRAP_CONTENT
).apply {
    weight = 1.0f
    gravity = Gravity.TOP
}
button.setLayoutParams(params)

For gravity values and how to set gravity check Gravity.

Basically, you should choose the LayoutParams depending on the parent. It can be RelativeLayout, LinearLayout etc...

Community
  • 1
  • 1
Karthi
  • 13,624
  • 10
  • 53
  • 76
  • 1
    For some reasons params.gravity = 80 (It should be BOTTOM, by te Docs) is just not working. I got some space betwen the bottom of the View and the Text. Its not so Bottom-aligned... – Adam Varhegyi Nov 10 '11 at 13:09
  • @AdamVarhegyi Without seeing your layout xml I'm not certain what your remaining problem is. But that space you're talking about may be due to padding. Try to [`setPadding()`](http://developer.android.com/reference/android/view/View.html#setPadding%28int,%20int,%20int,%20int%29) on your `View` to 0 for the bottom. – Tony Chan Nov 16 '11 at 03:23
  • 53
    Taking the constant value from the documentation is simply wrong, please use Gravity.TOP – Maragues Sep 22 '12 at 11:02
  • 52
    this is "gravity" and he asked for "layout_gravity" ?? – M. Usman Khan Mar 04 '16 at 14:02
  • 15
    @usman no, this is about `layout_gravity` (that is `LayoutParams.gravity`). The `gravity` would be `button.setGravity()` – Floern Nov 23 '16 at 17:06
  • 10
    There is a lot of wrong information about gravity and layout_gravity here on SO. Many ppl think that `setGravity()` is the layout_gravity, but this is wrong. I can approve that this answer is correct for setting layout_gravity programmatically. – Bevor Nov 28 '16 at 09:36
  • I think it is called gravity and not layoutGravity because it already is inside LayoutParams. – Michał Powłoka Apr 17 '18 at 09:33
61

I'd hate to be resurrecting old threads but this is a problem that is not answered correctly and moreover I've run into this problem myself.

Here's the long bit, if you're only interested in the answer, please scroll all the way down to the code:

android:gravity and android:layout_gravity work differently. Here's an article I've read that helped me.

GIST of article: gravity affects view after height/width is assigned. So gravity centre will not affect a view that is done MATCH_PARENT (think of it as auto margin). layout_gravity centre WILL affect view that is MATCH_PARENT (think of it as auto pad).

Basically, android:layout_gravity CANNOT be access programmatically, only android:gravity. In the OP's case and my case, the accepted answer does not place the button vertically centre.

To improve on Karthi's answer:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

params.gravity = Gravity.CENTER;
button.setLayoutParams(params);

Link to LinearLayout.LayoutParams.

android:layout_gravity shows "No related methods" meaning cannot be accessed programatically. Whereas gravity is a field in the class.

bighugedev
  • 379
  • 1
  • 3
  • 11
Uknight
  • 711
  • 6
  • 9
  • Also to add on that gravity auto-margins (for lack of a better term) based on the LinearLayout parent's orientation. The article link provided will help. – Uknight Nov 12 '12 at 10:25
23

I had a similar problem with programmatically setting layout_gravity on buttons in a GridLayout.

The trick was to set gravity on the button layoutParams AFTER the button was added to a parent (GridLayout), otherwise the gravity would be ignored.

grid.addView(button)
((GridLayout.LayoutParams)button.getLayoutParams()).setGravity(int)
owjsub
  • 231
  • 2
  • 4
20
MyButton.setGravity(Gravity.RIGHT);

For layout_gravity use the answer stated by "karthi". This method sets gravity to place the children inside the view.

Yashwanth Kumar
  • 28,931
  • 15
  • 65
  • 69
18
layoutParams2.gravity = Gravity.RIGHT|Gravity.BOTTOM;

use this to add mor than one gravity

Omar Alnajjar
  • 427
  • 5
  • 10
17

If you want to change the layout_gravity of an existing view, do this:

((FrameLayout.LayoutParams) view.getLayoutParams()).gravity = Gravity.BOTTOM;

Remember to use the right LayoutParams based on the Layout type your view is in. Ex:

LinearLayout.LayoutParams
bighugedev
  • 379
  • 1
  • 3
  • 11
vovahost
  • 34,185
  • 17
  • 113
  • 116
11

KOTLIN setting more than one gravity on FrameLayout without changing size:

     // assign more than one gravity,Using the operator "or"
    var gravity = Gravity.RIGHT or Gravity.CENTER_VERTICAL
     // update gravity
    (pagerContainer.layoutParams as FrameLayout.LayoutParams).gravity = gravity
     // refresh layout
     pagerContainer.requestLayout()
BertKing
  • 513
  • 5
  • 13
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
10

This question is old but I just had the same problem and solved it like this

LayoutParams lay = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)
lay.gravity = Gravity.CENTER;
CodeFlakes
  • 3,671
  • 3
  • 25
  • 28
  • @Muzikant.. ok.. i didnt noticed first.. but now its clear to me..Thanks – Noman Jul 18 '12 at 09:51
  • Does this only work by specifying what kind of layout it is first? Like RelativeLayout.LayoutParams ... instead of just LayoutParams – shecodesthings Oct 31 '12 at 18:48
  • RelativeLayout.LayoutParams use other flags to set gravity of the view (rightOf, centerInParent, centerVertical). This workaround is for LinearLayouts childrens – noni Sep 24 '13 at 20:41
5

If you want to put a view in the center of parent, you can do with following code..

public class myLayout extends LinearLayout {

    public myLayout(Context context) {
      super(context);

      RelativeLayout vi = (RelativeLayout) ((LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
            R.layout.activity_main, null);
      LinearLayout.LayoutParams cc = new LinearLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
      cc.gravity = Gravity.CENTER;
      this.setGravity(Gravity.CENTER);
      this.addView(vi);
  }
}

these code section make LinearLayout put the first view elements in the center of parent. So, we system don't consider the initial width and high to arrange view in the center . I do the code section well.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Cheng
  • 316
  • 3
  • 9
5

I use someting like that: (Xamarin and C# code)

  LinearLayout linLayout= new LinearLayout(this); 
    linLayout.SetGravity(GravityFlags.Center);

    TextView txtView= new TextView(this);  
     linLayout.AddView(txtView); 

the SetGravity puts my textView in the center of the layout. So SetGravity layout property refer to layout content

alin0509
  • 451
  • 4
  • 5
5

In case you need to set Gravity for a View use the following

Button b=new Button(Context);
b.setGravity(Gravity.CENTER);

For setting layout_gravity for the Button use gravity field for the layoutparams as

LayoutParams lp=new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
lp.gravity=Gravity.CENTER;

try this hope this clears thanks

user2779311
  • 1,688
  • 4
  • 23
  • 31
3

The rest of the answers are right, I want to add more explaination. The layout_gravity is about how to position the view in parent view.

You must set gravity **after method parentView.addView() ** was called. We can see the code:

public void setLayoutParams(ViewGroup.LayoutParams params) {
    if (params == null) {
        throw new NullPointerException("Layout parameters cannot be null");
    }
    mLayoutParams = params;
    resolveLayoutParams();
    if (mParent instanceof ViewGroup) {
        ((ViewGroup) mParent).onSetLayoutParams(this, params);
    }
    requestLayout();
}

And the problem of null pointer is because it's not calling addView before getLayoutParams().

The annotation was already said "This method may return null if this View is not attached to a parent ViewGroup or {@link#setLayoutParams(android.view.ViewGroup.LayoutParams)} was not invoked successfully. When a View is attached to a parent ViewGroup, this method must not return null."

Kristy Welsh
  • 7,828
  • 12
  • 64
  • 106
Snow Albert
  • 547
  • 7
  • 15
  • This bit me too...it's not obvious you have to set gravity after the addView() is called. You'd think you'd set everything up on the new view and then add it so this is unintuitive :-P – kenyee Aug 14 '16 at 03:23
3

Modify the existing layout params and set layout params again

//Get the current layout params and update the Gravity
(iv.layoutParams as FrameLayout.LayoutParams).gravity = Gravity.START
//Set layout params again (this updates the view)
iv.layoutParams = layoutParams
Sai
  • 15,188
  • 20
  • 81
  • 121
  • In my case there is LinearLayout inside FrameLayout, and gravity for LinearLayout works only if I cast it to FrameLayout, example: `@BindingAdapter("android:stateLayoutGravity") fun LinearLayout.setStateLayoutGravity(gravity: Int) { (this.layoutParams as FrameLayout.LayoutParams).apply { this.gravity = gravity } }` – bene25 Jun 29 '23 at 11:32
2

to RelativeLayout, try this code , it works for me: yourLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

michael wang
  • 553
  • 3
  • 11
2

Perfectly Working!!! None of the above answer works for me. In Xml file setting gravity and setting layout_gravity is different. Check out the below code

// here messageLL is the linear layout in the xml file
// Before adding any view just remove all views
   messageLL.removeAllViews();
// FrameLayout is the parent for LinearLayout
FrameLayout.LayoutParams params = new 
   FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
   params.gravity = Gravity.CENTER|Gravity.CENTER_VERTICAL;
   messageLL.setLayoutParams(params);
   messageText.setVisibility(View.GONE);
   messageNoText.setVisibility(View.VISIBLE);
   messageLL.addView(messageNoText);

Also check This,where you can find clear explanation about gravity and layout_gravity .

Tara
  • 2,598
  • 1
  • 21
  • 30
2

Most of above answer are right, so written a helper methods, so you can use it directly in you project .

set layout_gravity programmtically

// gravity types : Gravity.BOTTOM, Gravity.START etc.
// view : can be any view example : button, textview, linearlayout, image etc.

// for single view
   public static void setLayoutGravity(int gravity, View view){
     ((LinearLayout.LayoutParams) view.getLayoutParams()).gravity = gravity;
    }


// for mulitple views
  public static void setLayoutGravity(int gravity, View ...view){
        for(View item : view)
            ((LinearLayout.LayoutParams) item.getLayoutParams()).gravity = gravity;
    }
Abhishek Garg
  • 3,092
  • 26
  • 30
0

I switched from LinearLayout.LayoutParams to RelativeLayout.LayoutParams to finally get the result I was desiring on a custom circleview I created.

But instead of gravity you use addRule

RelativeLayout.LayoutParams mCircleParams = new RelativeLayout.LayoutParams(circleheight,circleheight);

    mCircleParams.addRule(RelativeLayout.CENTER_IN_PARENT);
0
 int width=getResources().getDisplayMetrics().widthPixels; 
 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
                    (width, width);

            params.gravity = Gravity.CENTER;

           iv_main_text = new HTextView(getContext());
            iv_main_text.setLayoutParams(params);
            iv_main_text.setBackgroundColor(Color.BLUE);
            iv_main_text.setTextSize(60);
            iv_main_text.setGravity(Gravity.CENTER);
            iv_main_text.setTextColor(Color.BLACK);
Manthan Patel
  • 1,784
  • 19
  • 23
0
FloatingActionButton sendFab = new FloatingActionButton(this);
    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(32, 32, 32, 32);
    layoutParams.gravity = Gravity.END|Gravity.BOTTOM;
    sendFab.setLayoutParams(layoutParams);
    sendFab.setImageResource(android.R.drawable.ic_menu_send);
VIVEK CHOUDHARY
  • 468
  • 5
  • 8
-1

Try this code

    Button btn = new Button(YourActivity.this);
    btn.setGravity(Gravity.CENTER | Gravity.TOP);
    btn.setText("some text");

or

    btn.setGravity(Gravity.TOP);
Fakhriddin Abdullaev
  • 4,169
  • 2
  • 35
  • 37