LayoutParams gravity not working

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

链接地址: http://www.djcxy.com/p/93278.html

上一篇: LinearLayout中的重力

下一篇: LayoutParams重力不起作用