Wiring up the UI with the Kotlin code (part 1)
To achieve an interactive app, we will do the following three things:
- We will call
setContentView
from theonCreate
function to show the progress of our UI when we run the app. - We will write two more functions of our own and each one will call
setContentView
on a different layout (that we have yet to design). - Then, later in this chapter, when we design two more UI layouts, we will be able to load them at the click of a button.
As we will be building a ConstraintLayout
and a TableLayout
, we will call our new functions, loadConstraintLayout
and loadTableLayout
, respectively.
Let's do that now, and then we'll see how we can add some buttons that call these functions alongside some neatly formatted text.
Inside the onCreate
function, add the following highlighted code:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_menu)
}
The code uses the setContentView
function to load the UI we are currently working on. You can now run the app to see the following results:
Add these two new functions inside the MainActivity
class after the onCreate
function:
fun loadConstraintLayout(v: View) { setContentView(R.layout.activity_main) } fun loadTableLayout(v: View) { setContentView(R.layout.my_table_layout) }
There is one error with the first function and two with the second. The first we can fix by adding an import
statement so that Android Studio is aware of the View
class. Left-click the word View
to select the error. Hold down the Alt key and then tap the Enter key. You will see the following popup:
Chose Import class. The error is now gone. If you scroll to the top of the code, you will see that a new line of code has been added by that shortcut we just performed. Here is the new code:
import android.view.View
Android Studio no longer considers the View
class an error.
The second function still has an error, however. The problem is that the function calls the setContentView
function to load a new UI (R.layout.my_table_layout
). As this UI layout does not exist yet, it produces an error. You can comment out this call to remove the error until we create the file and design the UI layout later this chapter. Add the double forward slash (//
), as highlighted in the following code:
fun loadTableLayout(v: View) {
//setContentView(R.layout.my_table_layout)
}
Now we can add some buttons that we can click to call our new functions and load the new layouts we will be building soon. But adding a couple of buttons with some text on is too easy – we have done that before. What we want to do is line up some text with a button to the right of it. The problem is that our LinearLayout
has the orientation
attribute set to vertical
and, as we have seen, all the new parts we add to the layout will be lined up vertically.