Add view in relativelayout programmatically android

Android RelativeLayout inside create + add view dynamically using coding activity file.

Relative layout is most flexible layout available to develop android applications because this is the only view that gives us the facility to move or add view at any location on activity. So in this tutorial we are creating a TextView inside relativelayout and after that setting up textview alignment at center horizontal and center vertical at the middle of activity screen. So here is the complete step by step tutorial for Add view in relativelayout programmatically android.

android-project-download-code-button

How to Add view in relativelayout programmatically android.

Code for MainActivity.java file.

 package com.addviewrelativelayoutprogrammatically_android_examples.com;

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

public class MainActivity extends Activity {

 RelativeLayout relativelayout;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 Button DynamicButton = new Button(MainActivity.this);
 
 relativelayout = (RelativeLayout)findViewById(R.id.relativelayoutID);
 
 LayoutParams layoutparams = new RelativeLayout.LayoutParams(
 LayoutParams.WRAP_CONTENT, 
 LayoutParams.WRAP_CONTENT 
 );

 
 layoutparams.addRule(RelativeLayout.CENTER_IN_PARENT);

 
 DynamicButton.setLayoutParams(layoutparams);

 
 DynamicButton.setText("Dynamic Button");

 
 relativelayout.addView(DynamicButton);
 
 DynamicButton.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 
 Toast.makeText(MainActivity.this, "Clicked on Dynamic button", Toast.LENGTH_LONG).show();
 
 }
 });
 
 }
}

Code for activity_main.xml layout file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.addviewrelativelayoutprogrammatically_android_examples.com.MainActivity"
 android:id="@+id/relativelayoutID" >

 

</RelativeLayout>

Screenshot :

Add view in relativelayout programmatically android

Click here to download Add view in relativelayout programmatically android project.