Android: Align Parent Bottom + Bottom margin programmatically

Asked

Viewed 280 times

0

Does anyone know how I can programmatically add a Relativelayout aligned at the bottom of the parent and include a margin or padding at the bottom of that same Relativelayout?

Ex.:

inserir a descrição da imagem aqui

  • Igor, you need to specify which parent class, because depending on the choice, the subclass of LayoutParams to be used and the technique to be used as well. In general you can use the attribute layout_gravity as bottom|right programmatically on LayoutParams and to add margin needs to be in a MarginLayoutParams and padding directly on View.

  • Parent class is Relativelayout as well

  • Igor, I will do a test here and if a response works. It will build the element programmatically or inflate it?

1 answer

1


To add programmatically I used the following code:

RelativeLayout r = new RelativeLayout(this);

// O padding eh setado direto na View
r.setPadding(100, 100, 100, 100);

// Recupero o pai
RelativeLayout rl = ((RelativeLayout) findViewById(R.id.parent));

// Soh para dar contraste com o background
rl.setBackgroundColor(getResources().getColor(R.color.red));

// Crio um LayoutParams para posicionar e dar tamanho para a View
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(400, 400);
// ou
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
    RelativeLayout.LayoutParams.WRAP_CONTENT,
    RelativeLayout.LayoutParams.WRAP_CONTENT
);

// Setando as margens
lp.setMargins(0, 0, 32, 32);

// Adiciono uma regra para alinhar o filho ao fundo do pai
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
// Adiciono as regras para alinha o filho no final do pai
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
// Suporte para layout RTL
lp.addRule(RelativeLayout.ALIGN_PARENT_END);

// Adiciono a View no pai, especificando o LayoutParams
rl.addView(r, lp);

Of course to give the expected effect the father needs to occupy all the space, using the MATCH_PARENT in relation to Window.

An example as it stood on my device:

Exemplo de alinhamento programático

  • hasn’t worked on mine yet, my dad layout is also done programmatically.

  • If you can, post the code you use to generate it, the example I did was with the father inflated by Activity.

  • I went to check the father of this layout and saw that was WRAP_CONTENT, so it worked. Thanks @Wakim

Browser other questions tagged

You are not signed in. Login or sign up in order to post.