enter image description here

From the picture, you can see that the xml CAN report errors, you just have to really break it. In this sense, it means that you have to type something which it cannot parse or make sense of, such as trying to define a property which doesn’t exist.

Now, in terms of your button click listener, the xml doesn’t really have any reference towards where it will be used, unless you tell it, by using context in your root layout :


Complete example:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    tools:context=".ui.overview.OverviewActivity"> //<-- this is key

enter image description here

But, this will also still compile and install and you won’t have any compile time issues here, so this won’t really help in your situation

Perhaps a better approach would be to ask why you’re still defining these click listeners in the xml, when kotlin offers us synthetic imports. Here’s an example:

Instead of defining the click listener in the xml file, like you’re doing, the following is also valid:

Assuming you have a basic button


now in the activity, you can just reference the button straight, by using:

    myButton.setOnClickListener { //this is the ID of the component in xml you're trying to access
      //your logic here

This is because of a feature kotlin has, called synthetic imports, which allows us to directly access xml components by importing the entire file, such as :

import kotlinx.android.synthetic.main.example.*

Why I think this is better ? (personal opinion)

This creates an additional separation between the xml and the implementation – by setting the click listener in the activity/fragment, this file is now entirely reusable somewhere else, so we can use it in another part of our app without having to define the same listeners everywhere and by only making use of synthetics to handle your event listeners, you actually will have compile time errors, preventing you from building if a component isn’t found

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top