2012-05-02 27 views
51

¿Puede darme un ejemplo muy simple de agregar vista hija programáticamente al RelativeLayout en una posición determinada?¿Cómo agregar una vista programmattically a RelativeLayout?

Por ejemplo, para reflejar el siguiente código 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"> 

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

No entiendo cómo crear un RelativeLayout.LayoutParams instancia apropiada.

Respuesta

91

Aquí está un ejemplo para que pueda empezar, rellenar el resto en su caso:

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); 

la documentación para RelativeLayout.LayoutParams y los constructores son here

+0

Lo siento, la misma pregunta: ¿dónde aprendiste acerca del constructor 'RelativeLayout.LayoutParams' sin un' Contexto' como primer parámetro? –

+1

@SuzanCioc Ver la edición anterior – JRaymond

+0

Ah, lo siento fue pensar que el ancho y la altura deberían ser valores exactos. –

27

En primer lugar, usted debe dar un id a su RelativeLayout digamos 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); 
+0

¿Dónde se describe el constructor 'RelativeLayout.LayoutParams'? No está aquí http://developer.android.com/reference/android/widget/RelativeLayout.html ya que todos los prototipos tienen 'Context' como primer parámetro. –

+1

Debe consultar aquí http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html Es RelativeLayout.LayoutParams (int w, int h) –

+0

¿Qué es 'R.id.relativeLayout1' ¿refiriéndose a? – Si8

Cuestiones relacionadas