From Layout XML to View Objects

How do XML elements in activity_main.xml become View objects? The answer starts in the MainActivity class.

When you created the GeoQuiz project, a subclass of Activity named MainActivity was created for you. The class file for MainActivity is in the app/java directory of your project.

A quick aside about the directory name before we get into how layouts become views: This directory is called java because Android originally supported only Java code. In your project, because you configured it to use Kotlin (and Kotlin is fully interoperable with Java), the java directory is where the Kotlin code lives. You could create a kotlin directory and place your Kotlin files there, but you would have to tell Android that the new folder includes source files so they would be included in your project. In most cases, separating your source files based on their language provides no benefit, so most projects just place their Kotlin files in the java directory.

MainActivity.kt may already be open in a tab in the editor tool window. If it is not, locate the app/java directory in the project tool window and click on it to reveal its contents, then click to reveal the contents of the com.bignerdranch.android.geoquiz package. (Not one of the packages with the name shaded green – those are the test packages. The production package is unshaded.) Open the MainActivity.kt file and take a look at its contents.

Listing 1.4  Default class file for MainActivity (MainActivity.kt)

package com.bignerdranch.android.geoquiz

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

(Wondering what AppCompatActivity is? It is a subclass of Android’s Activity class that provides compatibility support for older versions of Android. You will learn much more about AppCompatActivity in Chapter 14.)

If you are not seeing all of the import statements, click the + symbol to the left of the first import statement to reveal the others.

This file has one Activity function: onCreate(Bundle?).

The onCreate(Bundle?) function is called when an instance of the activity subclass is created. When an activity is created, it needs a UI to manage. To give the activity its UI, you call Activity.setContentView(layoutResID: Int).

This function inflates a layout and puts it onscreen. When a layout is inflated, each widget in the layout file is instantiated as defined by its attributes. You specify which layout to inflate by passing in the layout’s resource ID.

Resources and resource IDs

A layout is a resource. A resource is a piece of your application that is not code – things like image files, audio files, and XML files.

Resources for your project live in a subdirectory of the app/res directory. In the project tool window, you can see that activity_main.xml lives in res/layout/. Your strings file, which contains string resources, lives in res/values/.

To access a resource in code, you use its resource ID. The resource ID for your layout is R.layout.activity_main.

To see the current resource IDs for GeoQuiz, you must bravely explore into the world of auto-generated code – code that the Android build tool writes on your behalf. First, run the build tool by clicking the green hammer icon in the toolbar at the top of the Android Studio window.

By default, Android Studio displays the Android project view in the project tool window. This view hides the true directory structure of your Android project so that you can focus on the files and folders that you need most often. To see the files and folders in your project as they actually are, locate the dropdown at the top of the project tool window and change from the Android view to the Project view (Figure 1.15).

Figure 1.15  Project tool window: Android view vs Project view

Project tool window: Android view vs Project view

In the Project view, expand the GeoQuiz directory and keep going until you can see the contents of GeoQuiz/app/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/. In this directory, find your project’s package name and drill down until you find R.java within that package (Figure 1.16).

Figure 1.16  Viewing R.java

Viewing R.java

Double-click on the file to open it. Because R.java is generated by the Android build process, you should not change it, as you are subtly warned at the top of the file (Listing 1.5).

Listing 1.5  Current GeoQuiz resource IDs (R.java)

/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.bignerdranch.android.geoquiz;

public final class R {
    public static final class anim {
        ...
    }
    ...
    public static final class id {
        ...
    }
    public static final class layout {
        ...
        public static final Int activity_main=0x7f030017;
    }
    public static final class mipmap {
        public static final Int ic_launcher=0x7f030000;
    }
    public static final class string {
        ...
        public static final Int app_name=0x7f0a0010;
        public static final Int false_button=0x7f0a0012;
        public static final Int question_text=0x7f0a0014;
        public static final Int true_button=0x7f0a0015;
    }
}

By the way, you may not see this file instantly update after making a change to your resources. Android Studio maintains a hidden R.java file that your code builds against. The R.java file in Listing 1.5 is the one that is generated for your app just before it is installed on a device or emulator. You will see this file update when you run your app.

The R.java file can be large, and much of this file is omitted from Listing 1.5.

This is where the R.layout.activity_main comes from – it is an integer constant named activity_main within the layout inner class of R.

Your strings also have resource IDs. You have not yet referred to a string in code, but if you did, it would look like this:

    setTitle(R.string.app_name)

Android generated a resource ID for the entire layout and for each string, but it did not generate resource IDs for the individual widgets in activity_main.xml. Not every widget needs a resource ID. In this chapter, you will only interact with the two buttons in code, so only they need resource IDs.

To generate a resource ID for a widget, you include an android:id attribute in the widget’s definition. In activity_main.xml, add an android:id attribute to each button. (You will need to switch to the Text tab to do this.)

Listing 1.6  Adding IDs to Buttons (res/layout/activity_main.xml)

<LinearLayout ... >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="24dp"
        android:text="@string/question_text" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/true_button" />

        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/false_button" />

    </LinearLayout>

</LinearLayout>

Notice that there is a + sign in the values for android:id but not in the values for android:text. This is because you are creating the resource IDs and only referencing the strings.

Before moving on, change the project tool window from the Project view to the Android view. Throughout this book, the Android view will be used – but feel free to use the Project version if you prefer. Also, close R.java by clicking the x in its editor tab.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.6.75