boo-urns
boo-urns

Reputation: 10376

Add button to bottom of linear layout programmatically

I have a bunch of buttons displayed using the default gravity. The last button I add to the LinearLayout view is what I'd like to appear at the bottom of the view. How do I add it programmtically to appear at the bottom of the screen? I've tried setting the gravity, but everything falls to the bottom. I just want the one button to fall to the bottom of the screen. Ideally, I won't have to make another view.

Upvotes: 3

Views: 13311

Answers (2)

Rodrigo
Rodrigo

Reputation: 4802

Try this:

Button button = new Button(this);
youLinearLayout.addView(button, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM));

edit sorry, the code above dont work.

You cant do this using an single LinearLayout if orientation==vertical.

You'll need create another layout(RelativeLayout) and add TextView to it.

RelativeLayout relative = new RelativeLayout(this); 
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT );
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

relativeLayout.addView(textView, params);

linearLayout.addView(relativeLayout, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

Upvotes: 7

Roman Rdgz
Roman Rdgz

Reputation: 13254

If the rest of the screen is not empty, you can give android:layout_weight=0.0 to the Button, and 1.0 to the widget on the top.

In that way, widget with 1.0 weight will expand to fill empty areas, and Button with 0.0 will take only the default space, and being the last item addes to a vertical LinearLayout, it will be sticked to the bottom.

Upvotes: 4

Related Questions