2012-05-02 3 views
51

Puoi fornirmi un esempio molto semplice dell'aggiunta di una vista secondaria a livello di codice a RelativeLayout in una determinata posizione?Come aggiungere una vista programmaticamente a RelativeLayout?

Ad esempio, per riflettere il seguente codice 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" /> 

Non capisco come creare un adeguato RelativeLayout.LayoutParams esempio.

risposta

91

Ecco un esempio per iniziare, riempire il resto a seconda dei casi:

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 documentazione per RelativeLayout.LayoutParams e costruttori sono here

+0

Spiacente, la stessa domanda: dove hai saputo del costruttore 'RelativeLayout.LayoutParams' senza un' Context' come primo parametro? –

+1

@SuzanCioc Vedi modifica sopra – JRaymond

+0

Ah, mi spiace pensare che la larghezza e l'altezza dovrebbero essere valori esatti. –

27

In primo luogo, si dovrebbe dare un id al vostro RelativeLayout diciamo relativoLayout1.

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

Dov'è descritto il costruttore 'RelativeLayout.LayoutParams'? Non è qui http://developer.android.com/reference/android/widget/RelativeLayout.html poiché tutti i prototipi hanno 'Context' come primo parametro. –

+1

Dovresti controllare qui http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html È RelativeLayout.LayoutParams (int w, int h) –

+0

Che cosa è 'R.id.relativeLayout1' riferito a? – Si8