Wiring Up Widgets

You are ready to wire up your button widgets. This is a two-step process:

  • get references to the inflated View objects

  • set listeners on those objects to respond to user actions

Getting references to widgets

Now that the buttons have resource IDs, you can access them in MainActivity. Type the following code into MainActivity.kt (Listing 1.7). (Do not use code completion; type it in yourself.) After you save the file, it will report two errors. You will fix the errors in just a second.

Listing 1.7  Accessing view objects by ID (MainActivity.kt)

class MainActivity : AppCompatActivity() {

    private lateinit var trueButton: Button
    private lateinit var falseButton: Button

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

        trueButton = findViewById(R.id.true_button)
        falseButton = findViewById(R.id.false_button)
    }
}

In an activity, you can get a reference to an inflated widget by calling Activity.findViewById(Int). This function returns the corresponding view. Rather than return it as a View, it is cast to the expected subtype of View. Here, that type is Button.

In the code above, you use the resource IDs of your buttons to retrieve the inflated objects and assign them to your view properties. Since the view objects are not inflated into and available in memory until after setContentView(…) is called in onCreate(…), you use lateinit on your property declarations to indicate to the compiler that you will provide a non-null View value before you attempt to use the contents of the property. Then, in onCreate(…), you look up and assign the view objects the appropriate properties. You will learn more about onCreate(…) and the activity lifecycle in Chapter 3.

Now let’s get rid of those pesky errors. Mouse over the red error indicators. They both report the same problem: Unresolved reference: Button.

These errors are telling you that you need to import the android.widget.Button class into MainActivity.kt. You could type the following import statement at the top of the file:

    import android.widget.Button

Or you can do it the easy way and let Android Studio do it for you. Just press Option-Return (or Alt-Enter) to let the IntelliJ magic under the hood amaze you. The new import statement now appears with the others at the top of the file. This shortcut is generally useful when something is not correct with your code. Try it often!

This should get rid of the errors. (If you still have errors, check for typos in your code and XML.) Once your code is error free, it is time to make your app interactive.

Setting listeners

Android applications are typically event driven. Unlike command-line programs or scripts, event-driven applications start and then wait for an event, such as the user pressing a button. (Events can also be initiated by the OS or another application, but user-initiated events are the most obvious.)

When your application is waiting for a specific event, we say that it is listening for that event. The object that you create to respond to an event is called a listener, and the listener implements a listener interface for that event.

The Android SDK comes with listener interfaces for various events, so you do not have to write your own. In this case, the event you want to listen for is a button being pressed (or clicked), so your listener will implement the View.OnClickListener interface.

Start with the TRUE button. In MainActivity.kt, add the following code to onCreate(Bundle?) just after the variable assignments.

Listing 1.8  Setting a listener for the TRUE button (MainActivity.kt)

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

    trueButton = findViewById(R.id.true_button)
    falseButton = findViewById(R.id.false_button)

    trueButton.setOnClickListener { view: View ->
        // Do something in response to the click here
    }
}

(If you have an Unresolved reference: View error, try using Option-Return [Alt-Enter] to import the View class.)

In Listing 1.8, you set a listener to inform you when the Button known as trueButton has been pressed. The Android framework defines View.OnClickListener as a Java interface with a single method, onClick(View). Interfaces with a single abstract method are common enough in Java that the pattern has a pet name, SAM.

Kotlin has special support for this pattern as part of its Java interoperability layer. It lets you write a function literal, and it takes care of turning that into an object implementing the interface. This behind-the-scenes process is called SAM conversion.

Your on-click listener is implemented using a lambda expression. Set a similar listener for the FALSE button.

Listing 1.9  Setting a listener for the FALSE button (MainActivity.kt)

override fun onCreate(savedInstanceState: Bundle?) {
    ...
    trueButton.setOnClickListener { view: View ->
        // Do something in response to the click here
    }

    falseButton.setOnClickListener { view: View ->
        // Do something in response to the click here
    }
}
..................Content has been hidden....................

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