Google+

Android4Beginners.com

Apps development for Android step by step

Lesson 1.1: My first app: More than Hello world! (TextView tag and android:text attribute)

If you want to create an app displaying on the screen “Hello world!” (a standard text for the first application), just… start a new project in Android Studio. It already includes Hello world! functionality. But what to do to display “I’m the best!” instead?

There are two ways of doing it: very simple and… recommended one (but still simple). Firstly, you have to start a new project or open the one created in Lesson 0 and then find again activity_main.xml file in layout subfolder (you could learn how to open that file from Lesson 0). Now click Text tab at the bottom of the activity_main.xml file window. You should see the code of layout of your first app.

Click Text tab at the bottom so you could edit a code of XML file called activity_main.xml (Android Studio)

Click Text tab at the bottom so you could edit a code of XML file called activity_main.xml (Android Studio)

The code is quite long, but at the moment we’re interested only in the fragment with TextView.

TextView is so called XML tag. In this case you could treat it is as a command used to view a text on the screen (though XML keeps data not commands). In this example the tag has three attributes (parameters): android:layout_width, android:layout_height and android:text. An attribute is always a pair of name and value. Look through Appendix A to understand XML tags and attributes structure.

Let’s try to understand TextView. We already know what for is that tag (displaying text). So now a few words about its main attributes. Attributes android:layout_width and android:layout_height set size of the layout element (in our case an element displaying some text) . We will talk about them later.

Now we focus on android:text attribute. Its value is exactly a text shown on the screen. So change its value to “I’m the best” and look at preview or run app to see the effect (instruction for previewing and running apps is in Lesson 0).

 

Now you should see “I’m the best” text on the screen (Android Studio)

Now you should see “I’m the best” text on the screen (Android Studio)

Simple, isn’t it? But this is not recommended method. Why? Because it writes specific text into the code. It’s better to say that this TextView tag should display for instance a welcome text and keep a real text separately (you will see more benefits of such approach later).

By the way Android Studio even displays warning about that – if you keep a mouse cursor over that line with android:text attribute you would see: Hardcoded string “I’m the best”, should use @string resource.

In the next lesson we try to learn the recommended approach.

Previous:
Next: