Introduction
In this lab we will try our first steps with the Kotlin language and add click handling to our UI.
- Make sure you have an understanding of these Kotlin concepts, discussed during the lecture:
- Mutable and immutable variable declaration (var vs val)
- Null-safety, including safe calls and the !! operator
- Inferred types
Exercise 1: In-code GUI creation
- in MainActivity.kt onCreate():
- Create a vertical LinearLayout
- Add 10 buttons to it using a loop
- Make the Activity display the LinearLayout object instead of the default XML resource (using setContentView(..) ).
Exercise 2: ConstraintLayout practice
Change back your MainActivity so that it uses the XML resource activity definition.
- Divide View vertically into 2 (2/3 and 1/3, as shown on picture), using a guideline
- Top should have 1 TextView with long text
- Vertically centered w.r.t. guideline
- Horizontally constrained to edges of layout, with 32dp margin
- Width set to match constraint
- Add 2 Buttons to the bottom
- Vertically centered
- Create a horizontal chain of them
- Set chain to "spread inside"
- Horizontally constrainted to edges of the parent
Exercise 3: Click behaviour
- Set up a click handler for both buttons (see below for more details)
- For the 1st button, use the programmatic approach and make the click update the button to show the number of times it has been clicked. Each time it gets clicked, it should also add a word to the TextView (hint).
- For the 2nd button, use
XML onClick
and make it restart the counter. (Also try clearing the TextView)
Tips & Examples
Getting a reference to a UI element defined in XML
- you can access UI View Objects directly using its ID
myButton.text = "Hello"
- have to import
import kotlinx.android.synthetic.main.activity_main
where activity_main correspond to the activity you are working with. - ( this works thanks to View Binding of the Kotlin Android Extension)
- have to import
- alternatively, using the findViewById(..) method, you can get a handle for referencing XML-declared resources & view objects in code:
val b:Button = findViewById(R.id.myButton)
- this is the common approach in Java-based Android
Setting click listeners
- To set a click listener from the code, you can use Button.setOnClickListener( .. )
button1.setOnClickListener { view: View? -> Log.i(TAG, "View: ${view?.id} was clicked!") }
- Alternatively, you can specify android:onClick attribute of the XML object definition, setting its value to the name of the method to be called
- The method has to be defined in the Activities' .kt file and accept a single argument of type View:
fun myHandler(view: View) { /** react to click */ }
- The method has to be defined in the Activities' .kt file and accept a single argument of type View: