65

Can you give me a very simple example of adding child view programmatically to RelativeLayout at a given position?

For example, to reflect the following 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" />

I don't understand how to create an appropriate RelativeLayout.LayoutParams instance.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385

2 Answers2

106

Heres an example to get you started, fill in the rest as applicable:

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

The docs for RelativeLayout.LayoutParams and the constructors are here

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
JRaymond
  • 11,625
  • 5
  • 37
  • 40
29

Firstly, you should give an id to your RelativeLayout let say 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);
Onuray Şahin
  • 344
  • 2
  • 4
  • Where is `RelativeLayout.LayoutParams` constructor described? It is not here http://developer.android.com/reference/android/widget/RelativeLayout.html since all prototypes have `Context` as first parameter. – Suzan Cioc May 02 '12 at 20:01
  • 1
    You should check here http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html It is RelativeLayout.LayoutParams(int w, int h) – Onuray Şahin May 03 '12 at 07:42
  • What is `R.id.relativeLayout1` referring to? – Si8 Aug 06 '13 at 12:05
  • @SiKni8 It is the id of the TextView parent Layout, a Relative layout that is already on the xml file. – joao2fast4u Aug 22 '14 at 09:16