1

Basically, I have this layout structure: <RelativeLayout> <RelativeLayout> <TextView /> </RelativeLayout> <ScrollView> <RelativeLayout> ... </RelativeLayout> </ScrollView> </RelativeLayout> and I want to add a button programmatically. This button should be inside the <RelativeLayout>, which is inside the <ScrollView>. Also, I need it to be align to the bottom and CENTER_VERTICAL. I would really appreciate any hints/examples ;) Thanks! P.S. Although, there are many similar questions on stackoverflow, none of the answers helped me...

1
  • 1
    select xml and press CTRL+SHIFT+K to format the code so that it will be looks good. Commented Jan 2, 2012 at 8:12

1 Answer 1

8

First you need to give your relative Layout in XML an ID: android:id="@+id/myLayout". Then in Java code:

Button b = new Button(this);
RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rl.addRule(RelativeLayout.ALIGN_BOTTOM);
b.setLayoutParams(rl);
((RelativeLayout) findViewById(R.id.myLayout)).addView(b);
Sign up to request clarification or add additional context in comments.

4 Comments

Thank You so much! I also added params.bottomMargin = 20; for a nicer look and change my .xml file, because the RelativeLayout there had 'WRAP_CONTENT' and it was impossible to align my button to the bottom.
I was also interested if I can "say" programmatically, that the newly created button should be below some TextView, for instance? Thanks.
Sure you can: rl.addRule(RelativeLayout.BELOW, R.id.textview01);
buttons are getting on top of each other, how to make them go right side and if space is full then below. Please help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.