Android: how to center a button programatically created?

I need to create a button programatically and have it centered on the layout, both horizontally and vertically. I am trying with the following code:

LinearLayout ll = (LinearLayout)findViewById(R.id.layoutItem);
Button b = new Button(this);        
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.button));
b.setLayoutParams(new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)); 
b.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
ll.addView(b);

But it's not working. The button comes out on top all to the left.

Any clues on how to fix this?

Answers


I would do something like:

LinearLayout.LayoutParams ll = (LinearLayout.LayoutParams)b.getLayoutParams();    
ll.gravity = Gravity.CENTER;
b.setLayoutParams(ll);

see if that works.


Or you can use a RelativeLayout as your parent View and do the following:

this.testButton= (Button) this.findViewById(R.id.testButton);

RelativeLayout.LayoutParams testLP = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

testLP.addRule(RelativeLayout.CENTER_IN_PARENT);

this.testButton.setLayoutParams(testLP);

You can set several rules for the RelativeLayout.


Need Your Help

AngularJS get formatted date in ng-model

javascript angularjs date

I have following text input filled by model value in timestamp: