Skip to content

Half Dozen Hello Worlds Part 2 – Using Layout XML

In order to make our TextView accessible in our code we’re going to start by opening main.xml in /res/layout and editing it like so:

12-Updated Main XML

We’ve removed the line


and replaced it with the line


The @+id tells Android that we are giving the TextView an ID inside of our Application Namespace.  This will allow us to access it in our code.  Let’s open up in our src folder.

package com.learnandroid.hellowworld;
import android.os.Bundle;
import android.widget.TextView;
public class Hello2 extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        TextView label = (TextView) findViewById(;
        label.setText("Hello World");

We’ve added two lines of code.  The first:

TextView label = (TextView) findViewById(;

uses the findViewById method to get the View, which we cast to a TextView.  Notice how our automatically generated R class automatically provides us with the id we defined in main.xml.  The next line:

label.setText("Hello World");

Simply sets the text to Hello World.  If you run this application now you should see (once again) Hello World on your screen.  That wraps up part 2.  Make sure to check out Part 3 of the series where we explore two kinds of pop-up messages available in Android.

{ 4 } Comments

  1. | November 15, 2010 at 5:01 am | Permalink

    Great ! this post is very useful . I will follow your blog.

    Thank you : )

  2. Jaydeep | May 10, 2011 at 1:02 pm | Permalink

    hey nice explanation of the Layouts. I really understood layouts better than what I understood from Google docs for Android layouts.

    Thanks a lot.

  3. Sam | June 7, 2011 at 2:21 am | Permalink

    obsolutely excellent acticle and tutorial for beginner, clear and coherent. the best i have seen.

  4. Bhagyashree | August 30, 2012 at 2:59 am | Permalink

    nice &helpful

{ 3 } Trackbacks

  1. […] separated out of the code and placed into an XML file.  We’ll look at how to do this next in Part 2 of this series. Posted by Sheridan on Monday, November 16, 2009, at 11:01 pm. Filed under […]

  2. […] Part 2 explored using a Layout XML. […]

  3. […] That’s because we are going to use Intents to call the programs we created in Part 1 and Part 2 of this […]

Post a Comment

Your email is never published nor shared. Required fields are marked *