Advertisements

Aatul Palandurkar

Adding TextView in Android

Posted on: July 30, 2013

Objectives :

  • How to set TextView in Android?
  • How to add TextView in Android?
  • How to add TextView in Android via Java program?
  • How to set Layout parameters from Java code in Android?

TextView is a one of the Views available in Android. There are two (2) ways to add TextView in your Android application as follows :

  1. Using XML code
  2. Using Java code

XML Code example – Adding to a TextView in a layout xml file

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" >

 <TextView
  android:id="@+id/textView"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Hello World" />

</LinearLayout>

 

Java Code example – Creating and adding a new TextView to a Layout

// Creates object of TextView
TextView textView = new TextView(this);
// Set text to display in TextView on Screen
textView.setText(“Hello World”);
// Add TextView to Linear Layout with layout parameters
((LinearLayout)findViewById(R.id.mainLayout))
 .addView(textView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

Above Java code can be written in onCreate() of your Activity.

Here LayoutParams.FILL_PARENT will set layout height to FILL_PARENT, LayoutParams.WRAP_CONTENT will set layout width to WRAP_CONTENT.

Posted from WordPress for Android

Advertisements

2 Responses to "Adding TextView in Android"

Reblogged this on Android apps and commented:
Don’t forget Max Battery Booster: https://play.google.com/store/apps/details?id=com.faygroup.maxbatterybooster

Like

Thanks a lot for re-blogging this tutorial on your site/blog.

Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Advertisements

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 8,341 other followers

Tweets

%d bloggers like this: