Layouts define which Views show up on your app screen.
To start with, we will deal with three types of views:
TextView: a text label
EditText: text entry box (user can type into it)
Button: a button!
Static vs Dynamic: Your views don’t do much of anything until you create them as Java objects.
ID attribute
Your view must have an ID attribute before you can create it as a Java Object. Otherwise Java can’t find the View.
Go to your layout. In layout designer view:
I’ve clicked the view (a TextView in this case) in the Component Tree, then type in an ID (“helloLabel”) to the ID attribute field.
You can also add an ID in the text (XML) editor:
Here’s a fast way to add the “ID” attribute:
- Create a blank line inside the View’s XML tag, between < and />.
- type “id” in this new line
- Hit enter TWICE until it says this: android:id=”@+id/”
- Type in the ID for the View.
Declaring Views
Declare your views just inside your class.
(declaring gives a name, but it doesn’t create the object yet.)
Example:
Notice that “TextView hello;” is NOT inside a method. It is just inside the class declaration.
TextView is the type of object you’re declaring, and hello is the name of the object.
Use “Alt-Enter” to import the TextView class.
It is declared in the class so you’ll be able to access it within any method in this class. If you instead declare it inside one of the methods, you will only be able to access it from within the scope of that method.
Creating the View Object
In your onCreate() method, create the view:
- The name hello matches the object you declared above.
- The findViewById() method finds a View from your XML layout file.
- “R” in “R.id.helloLabel” stands for Resources (i.e. “res” folder)
- The id must match the id of an object in the layout file.
The above works in Android Studio 3. If using Android Studio 2:
You need to type cast your View a TextView like this:
With that line selected in the editor, you can hit “Alt-Enter” and then enter again as a shortcut to type cast an object in Android Studio 2.
This example has two different types of names:
hello is the name of a Java object.
helloLabel is the ID attribute of the View in the XML layout file.
Now what?
Now your Java code can access and modify the View.