Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: how to center a button programatically created?

Tags:

android

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?

like image 615
Daniel Scocco Avatar asked Jul 25 '12 19:07

Daniel Scocco


2 Answers

I would do something like:

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

see if that works.

like image 84
0gravity Avatar answered Nov 10 '22 01:11

0gravity


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.

like image 40
prolink007 Avatar answered Nov 10 '22 01:11

prolink007