Create Button dynamically through MainActivity in android

Android create Button programmatically.

In this tutorial i am making a button widget through MainActivity.java programming file. Creating button through this procedure are called as dynamic button. So here is the complete step by step tutorial for Create Button dynamically through MainActivity in android.

android-project-download-code-button

How to Create Button dynamically through MainActivity in android.

Code for MainActivity.java file.

package com.android_examples.com.dynamicbuttonandroid;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 
 LinearLayout linearLayout = new LinearLayout(this);
 Button button = new Button(this);
 button.setText(" Button Programmatically ");
 button.setTextSize(20);
 button.setGravity(Gravity.CENTER);
 
 linearLayout.addView(button);
 
 this.setContentView(linearLayout, new LinearLayout.LayoutParams(
 LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

 }
}

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.android_examples.com.dynamicbuttonandroid.MainActivity" >

</RelativeLayout>

Screenshot :

Create Button dynamically through MainActivity in android

Click Here To Download Create Button dynamically through MainActivity in android project.

Leave a Reply

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