Home > OS >  Kotlin- How to access an Object/Shared Instance inside an XML file
Kotlin- How to access an Object/Shared Instance inside an XML file

Time:10-15

I'm an iOS developer currently learning Android development using Kotlin. I have an object/shared instance(iOS term):

object AppAppearance {
    val cornerRadius = "10dp"
}

enter image description here

How can I access the above inside an XML file?

<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <corners android:radius="${AppAppearance.cornerRadius}"/> // <---- This doesn't work
    <solid android:color="@android:color/holo_green_dark"/>

</shape>

enter image description here

CodePudding user response:

If you have constants you want to use in XML, you should define them in XML, not in Kotlin. For example, in res/values/ create a file named appearance.xml and put:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="cornerRadius">10dp</dimen>
</resources>

You can put other line items in this file in the resources block.

And in your file that uses it:

<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <corners android:radius="@dimen/cornerRadius"/>
    <solid android:color="@android:color/holo_green_dark"/>

</shape>

It is possible to read values from Kotlin using data binding, but that's not for constants. It reads member properties or functions of the activity/fragment that the view is attached to.

If all this seems convoluted and messy, that's because it is. The Jetpack Compose UI system is their new way of creating UI directly in Kotlin code so you aren't having to jump back and forth between languages. But its also a completely different model of how to do UI (the UI is built from the data model with logic instead of you imperatively hooking up a UI to the data), so it's not a direct replacement. You might find that you prefer it though.

  • Related