3

I have a parent LinearLayout with MATCH_PARENT for width and height .I am trying to figure out setting gravity and layout_gravity with java code.

LinearLayout l=new LinearLayout(this);
l.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams ll=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
l.setLayoutParams(ll);
l.setOrientation(LinearLayout.VERTICAL);

Now i am adding a Button to it using the following code :

LayoutParams llb=new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
llb.gravity=Gravity.RIGHT;
b.setLayoutParams(llb);

Now if i add this Button to LinearLayout l and make it the content view

l.addView(b);
setContentView(l);

all things are working properly. The button shows up in the Center and on the right side.

But if i embed this Button in a LinearLayout and then add this LinearLayout to the outer Layout as below

LinearLayout l2=new LinearLayout(this);
        l2.setOrientation(LinearLayout.HORIZONTAL);
        LinearLayout.LayoutParams ll2=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        l2.setLayoutParams(ll2);
        l2.addView(b);

// add this to main layout .The button has the same LayoutParams as above.

l.addView(l2);
            setContentView(l);

the Button always appears on the left and this

  llb.gravity=Gravity.RIGHT;

does not seem to work.

kindly update why this is not working.

thanks

user2779311
  • 1,688
  • 4
  • 23
  • 31
  • Try using `l2.setGravity(Gravity.RIGHT);` – Rehan Sep 07 '14 at 07:51
  • 2
    i am interested to know why this is not working rather than a workaround. i know i can do through setGravity. – user2779311 Sep 07 '14 at 07:52
  • @shayanpourvatan to place the button within the linearlayout that has width set to match_parent you dont need gravity you need layout_gravity since button width is wrap_content and setting gravity to button will have no effect .gravity for button is only to move the text within button boundary and not move the button within the layout. – user2779311 Sep 07 '14 at 08:16
  • 1
    Gravity on horizontal linear layout doesn't work http://stackoverflow.com/q/4783896/2627680 – headsvk Sep 07 '14 at 08:57
  • @headsvk thanks .that is the real reason. – user2779311 Sep 07 '14 at 09:15

0 Answers0