2.2 Add user interactivity
1. Introduction
What you’ll learn
- How to get user input using an EditText view.
- How to set text to a TextView view using the text from the EditText view.
- How to work with View and ViewGroup.
- How to change the visibility of a View.
What you’ll do
- Add interactivity to the AboutMe app, which is from a previous codelab.
- Add an EditText so the user can enter text.
- Add a Button and implement its click handler.
6. Task: Add a TextView to display the nickname
You can show or hide views in your app using the visibility attribute. This attribute takes one of three values:
- visible: The view is visible.
- Invisible: Hides the view, but the view still takes up space in the layout.
- gone: Hides the view, and the view does not take up any space in the layout.
7. Task: Add a click listener to the DONE button
A click handler on the Button object (or on any view) specifies the action to be performed when the button (view) is tapped. The function that handles the click event should be implemented in the Activity that hosts the layout with the button (view).
The click listener has generically this format, where the passed in view is the view that received the click or tap.
private fun clickHandlerFunction(viewThatIsClicked: View) {
// Add code to perform the button click event
}
You can attach the click-listener function to button click events two ways:
-
In the XML layout, you can add the android:onClick attribute to the element. For example:
<Button android:id="@+id/done_button" android:text="@string/done" ... android:onClick="clickHandlerFunction"/>
-
You can do it programmatically at runtime, in onCreate() of the Activity, by calling setOnClickListener. For example:
myButton.setOnClickListener { clickHanderFunction(it) }
In MainActivity.kt
, at the end of addNickname()
function, add the following code. If you’d like more information on how this code works, see the hideSoftInputFromWindow documentation.
// Hide the keyboard.
val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
8. Task: Add a click listener to the nickname TextView
At the end of the updateNickname
function, set the focus to the EditText
view. Use the requestFocus()
method.
// Set the focus to the edit text.
editText.requestFocus()
At the end of the updateNickname function, add code to make the keyboard visible.
// Show the keyboard.
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(editText, 0)