Android: Align Parent Bottom + Bottom margin programmatically

Igor Ronner picture Igor Ronner · Aug 25, 2014 · Viewed 23.9k times · Source

How can I programatically add a RelativeLayout that is aligned to the bottom of parent, and add a margin or padding in the same RelativeLayout?

Example:

enter image description here

Answer

Simas picture Simas · Aug 25, 2014

Here's how you can do that:

// Get the parent layout
RelativeLayout parent = (RelativeLayout) findViewById(R.id.parent);

// Create your custom layout
RelativeLayout relativeLayout = new RelativeLayout(this);
// Create LayoutParams for it // Note 200 200 is width, height in pixels
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(200, 200);
// Align bottom-right, and add bottom-margin
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.bottomMargin = 100;

relativeLayout.setLayoutParams(params);
relativeLayout.setBackgroundColor(Color.BLUE);
// Add the custom layout to your parent layout
parent.addView(relativeLayout);