Need help setting isVisible to false in a function

problem is at the last line in the code, I want to to set datePicker.isVisible to false but it can’t reference datePicker inside a function. the idea is to remove the datePicker once the user chooses the date

class MainActivity : AppCompatActivity() {
    var message: String = ""  //the message will be stored here
    var newMonth: Int = 0  //the calendar returns month that starts at 0(january=0, february=1, etc.)
    //                       but we want the months to start at 1(january=1). so we make this variable equal to
    //                       month+1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //referencing the UI:
        val datePicker: CalendarView = findViewById(R.id.calender)

        datePicker.isVisible = true
        datePicker.setOnDateChangeListener {_, year, month, day -> formatDate(year, month, day)}
    }

    private fun formatDate(year: Int, month: Int, day: Int) {
        newMonth = month+1
        message = "$day.$month.$year"
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
        datePicker.isVisible = false  //doesn't work, can't reference datePicker in a function... how do I reference it?

    }

The variable datePicker is bound to the scope of the onCreate function. When the onCreate function is finished, the variable datePicker is destroyed. That is why you cannot reference the datePicker variable outside the onCreate function (i.e. in formatDate)

One solution would be to turn the datePicker variable into a class member variable (i.e. a property)

class MainActivity : AppCompatActivity() {
    var message: String = ""
    var newMonth: Int = 0
    private lateinit var datePicker: CalendarView
    /* function declarations */
}

All member functions (i.e. methods) will be able to access your member variables since member variables are bound to the lifetime of the MainActivity object.

1 Like

thanks!

1 Like

For clarity of code, please consider the following:

Currently you pass the parameter values of setOnDateChangeListener to your function formatDate - except for the first parameter. What is this first parameter? It is the reference to the calendar view associated to this listener - or in other words: exactly the object you want (datePicker).

That means that you don’t need an attribute/property in the class, you can just add the parameter to the function:

private fun formatDate(datePicker: CalendarView, year: Int, month: Int, day: Int) {

and the parameter can be passed to the call of formatDate like the other parameters. And since the parameters of the expected listener (function) and your function are now identical, the call can be simplified:

datePicker.setOnDateChangeListener(this::formatDate)

Note: I haven’t tested the source code snippets, just wrote them here. I apologize for any typos.