To accomplish this feat is to use the RelativeLayout.LayoutParams , passing the getLayoutParams()
in the view window. Here is an example using a simple button: Jon Snow . See comments. See:
// 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 placements:
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);
Center vertical / horizontal
rlp.addRule(RelativeLayout.CENTER_VERTICAL,RelativeLayout.CENTER_HORIZONTAL);
Formoredetailsandplacements,see in the documentation .