How to add a view programmatically to RelativeLayout?

AndroidAndroid LayoutAndroid Relativelayout

Android Problem Overview


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.

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSuzan CiocView Question on Stackoverflow
Solution 1 - AndroidJRaymondView Answer on Stackoverflow
Solution 2 - AndroidOnuray ŞahinView Answer on Stackoverflow