web-dev-qa-db-fra.com

Comment ajouter une vue par programme à RelativeLayout?

Pouvez-vous me donner un exemple très simple d'ajout d'une vue enfant par programme à RelativeLayout à un emplacement donné?

Par exemple, pour refléter le XML suivant:

<?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">

<TextView
    Android:id="@+id/textView1"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:layout_alignParentLeft="true"
    Android:layout_alignParentTop="true"
    Android:layout_marginLeft="107dp"
    Android:layout_marginTop="103dp"
    Android:text="Large Text"
    Android:textAppearance="?android:attr/textAppearanceLarge" />

Je ne comprends pas comment créer une instance appropriée RelativeLayout.LayoutParams.

57
Suzan Cioc

Voici un exemple pour vous aider à démarrer. Remplissez le reste, le cas échéant:

TextView tv = new TextView(mContext);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.leftMargin = 107
...
mRelativeLayout.addView(tv, params);

Les docs pour RelativeLayout.LayoutParams et les constructeurs sont ici

98
JRaymond

Tout d’abord, vous devriez donner un identifiant à votre RelativeLayout, en disant: relativeLayout1.

RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.relativeLayout1);
TextView mTextView = new TextView(context);
mTextView.setText("Dynamic TextView");
mTextView.setId(111);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
mainLayout.addView(mTextView, params);
29
Onuray Şahin