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:
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
Great ! this post is very useful . I will follow your blog.
Thank you : )
hey nice explanation of the Layouts. I really understood layouts better than what I understood from Google docs for Android layouts.
Thanks a lot.
obsolutely excellent acticle and tutorial for beginner, clear and coherent. the best i have seen.
nice &helpful
{ 3 } Trackbacks
[…] 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 […]
[…] Part 2 explored using a Layout XML. […]
[…] 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