Data Validation and Error Handling
Learn and practice how to validate user input text and show error messages in this lesson.
We'll cover the following...
View binding
Because we are going to use view references across different methods, we need to declare binding
as a global variable (1).
Press + to interact
class LoginActivity : AppCompatActivity() {private lateinit var binding: ActivityLoginBinding // 1override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)binding = ActivityLoginBinding.inflate(layoutInflater)setContentView(binding.root)}}
Validation & error message
To perform validation, we need to set a click listener on the login button via the setOnClickListener
method, which accepts the OnClickListener
interface as a parameter. When the login button is clicked, we execute our onLoginClicked
method.
Press + to interact
class LoginActivity : AppCompatActivity() {private lateinit var binding: ActivityLoginBindingoverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)binding = ActivityLoginBinding.inflate(layoutInflater)setContentView(binding.root)binding.loginButton.setOnClickListener(object : View.OnClickListener {override fun onClick(v: View?) {onLoginClicked()}})}}
Click listener anonymous object implementation (1) can be slightly simplified to anonymous function (2) or lambda (3).
In Kotlin, if lambda is the last parameter it can be moved outside function parentheses (4). ...