Monday, May 25, 2015

How to create a RelativeLayout programmatically in Android

MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

public class MainActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Initialize a new RelativeLayout
        RelativeLayout rl = new RelativeLayout(getApplicationContext());
        // Create LayoutParams for RelativeLayout
        LayoutParams lp = new RelativeLayout.LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT
        );

        // Set RelativeLayout LayoutParams
        rl.setLayoutParams(lp);
        // Set a background color for RelativeLayout
        rl.setBackgroundColor(Color.parseColor("#FF2C9DFF"));


        // Initialize a new TextView widget
        TextView tv = new TextView(getApplicationContext());

        // Create a LayoutParams for TextView widget
        LayoutParams lp_tv = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT
        );

        // Specify the TextView position in parent layout
        lp_tv.addRule(RelativeLayout.CENTER_IN_PARENT);

        // Add LayoutParams to TextView
        tv.setLayoutParams(lp_tv);

        // Set a text for TextView
        tv.setText("Sample TextView");

        // Set padding for TextView
        tv.setPadding(15,15,15,15);

        // Set a background color to TextView
        tv.setBackgroundColor(Color.RED);

        // Ad the TextView to RelativeLayout as child View
        rl.addView(tv);

        // Finally, specify the RelativeLayout is the root content
        setContentView(rl);
   }
}
More android examples