Monday, May 25, 2015

How to add a View to RelativeLayout programmatically in Android

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="@android:color/white"
    >
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

public class MainActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);

        // Initializing a new Button widget
        Button btn = new Button(getApplicationContext());

        // Create LayoutParams for Button widget
        LayoutParams lp = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, // Width
                LayoutParams.WRAP_CONTENT // Height
        );

        // Specify Button position in layout center
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);

        // Add LayoutParams to Button widget (View)
        btn.setLayoutParams(lp);

        // Set a text for Button
        btn.setText("Sample Button");

        // Finally, add the Button to RelativeLayout
        rl.addView(btn);
    }
}
More android examples