Android create textview programmatically example

Dynamically add textview to display text on android application inside linearLayout using textview widget assign.

TextView widget can be easily build through MainActivity.java programming file without adding layout xml file inside android application. This type of textview is purely created through programming method so its more perfect and gives more accessibility to application developer. So here is the complete step by step tutorial for Android create textview programmatically example.

android-project-download-code-button

Android create textview programmatically example.

Code for MainActivity.java file.

 package com.textviewprogrammatically;

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


public class MainActivity extends Activity {

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

</RelativeLayout>

Screenshot:

Android create textview programmatically example

Click Here to download Android create textview programmatically example project.

Leave a Reply

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