Search code examples
androidkotlindata-class

Text in button is not displayed


This is the class

data class Crime(
val id:UUID=UUID.randomUUID(),
var title:String="",
var date: Date= Date(),
var isSolved:Boolean=false)

I want to display current date as a text in button.(Below is the layout for button)

<Button
    android:id="@+id/crime_date"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:text="Wed Nov 14 11:56 EST 2018"/>

This is the .kt code to set the text in button

crime_date?.apply {
            text = crime.date.toString()
            isEnabled = false
        }

Solution

  • Tools is just for development, text is the property that you want to set, to see when the app is built.

    <Button
        android:id="@+id/crime_date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:text="Wed Nov 14 11:56 EST 2018"/>
    

    should be

    <Button
        android:id="@+id/crime_date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Wed Nov 14 11:56 EST 2018"/>
    

    Check if you have a property text declared your app, before setting in apply, like

    var text = ""
    crime_date?.apply {
                text = crime.date.toString()
                isEnabled = false
            }
    

    try if

    crime_date?.text = "data" 
    

    is working, if it is working the problem is with the crime.date.toString() part, try to debug with breakpoints, to check the values.

    Edit:

    If the code is called from a fragment make sure that it is called in or after onViewCreated, like:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            crime_date?.apply {
                text = crime.date.toString()
                isEnabled = false
            }
        }