Create RelativeLayout programmatically android example

Dynamically design android user interface design layout using MainActivity.java coding file.

Android development programming provide its developer to facility to design android application user interface design using programmatically method without using layout xml file purely design through MainActivity.java programming file. So here is the complete step by step tutorial for Create RelativeLayout programmatically android example.

android-project-download-code-button

How to Create RelativeLayout programmatically android example.

Code for MainActivity.java file.

 package com.relativelayoutprogrammaticallyandroid_examples.com;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
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);
 
 RelativeLayout relativelayout = new RelativeLayout(this);
 Button btn = new Button(this);
 
 LayoutParams layoutparams = new RelativeLayout.LayoutParams(
 LayoutParams.MATCH_PARENT,
 LayoutParams.MATCH_PARENT
 );
 LayoutParams LayoutParamsButtons = new RelativeLayout.LayoutParams(
 LayoutParams.WRAP_CONTENT,
 LayoutParams.WRAP_CONTENT
 );
 relativelayout.setLayoutParams(layoutparams);
 
 relativelayout.setBackgroundColor(Color.parseColor("#fa0303"));
 LayoutParamsButtons.addRule(RelativeLayout.CENTER_IN_PARENT);
 btn.setLayoutParams(LayoutParamsButtons);
 btn.setText("Button Name");
 btn.setBackgroundColor(Color.BLUE);
 relativelayout.addView(btn);
 setContentView(relativelayout);
 }
}

Code for activity_main.xml layout file.

 You don't need to use layout.xml file.

Screenshot :

Create RelativeLayout programmatically android example

Click Here to download Create RelativeLayout programmatically android example project.

Leave a Reply

Your email address will not be published. Required fields are marked *