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

android:text=”@string/hello”

and replaced it with the line

android:id=”@+id/label”

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 Hello2.java in our src folder.

package com.learnandroid.hellowworld;
 
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
 
public class Hello2 extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView label = (TextView) findViewById(R.id.label);
        label.setText("Hello World");
 
    }
}

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

TextView label = (TextView) findViewById(R.id.label);

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