To accomplish this feat is using the Relativelayout.Layoutparams, passing the method getLayoutParams()
in view desired. Below follows an example using a simple button: Jon Snow. See comments. View:
// RelativeLayout referente ao XML
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relative);
// botão a ser positionado
Button btnJonSnow= new Button(this);
btnJonSnow.setText("Jon Snow");
// definição da largura e altura do botão
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
relativeLayout.addView(btnJonSnow, layoutParams);
//propriedades do Relative Layout para o posicionamento
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) btnJonSnow
.getLayoutParams();
rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
btnJonSnow.setLayoutParams(rlp);
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/relative">
</RelativeLayout>
See below the basic positions:
Top/Left
rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
Top/Right
rlp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
Footer/Left
rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,RelativeLayout.ALIGN_PARENT_LEFT);
Footer/Right
rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,RelativeLayout.ALIGN_PARENT_RIGHT);
Vertical/horizontal center
rlp.addRule(RelativeLayout.CENTER_VERTICAL,RelativeLayout.CENTER_HORIZONTAL);
For more details and positions, see in the documentation.