Create TextView dynamically using java file in android

Android create textview programmatically.

On every android applications there are multiple ways to define textView or any other widgets first one is using activity_main.xml file and second is through MainActivity.java programming file. So here is the complete step by step tutorial for Create TextView dynamically using Java file in android.

android-project-download-code-button

Create TextView dynamically using Java file in android.

Code for MainActivity.java file.

 package com.android_examples.com.dynamictextviewandroid;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 LinearLayout linearLayout = new LinearLayout(this);
 TextView txtView = new TextView(this);
 txtView.setText(" TextView Programmatically ");
 txtView.setTextSize(20);
 txtView.setPadding(20, 300, 20, 100);
 
 linearLayout.addView(txtView);
 
 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.dynamictextviewandroid.MainActivity" >

 
</RelativeLayout>

Screenshot :

Create TextView dynamically using java file in android

Click Here To Download Create TextView dynamically using java file in android project.

Leave a Reply

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