androidimagekotlindrawable

Get images from drawable programmatically and load each day of the week (day or night) in Android Kotlin


I have a Kotlin Code to show images during day & night (imageday.png & imagenight.png) Here is the code:

private fun getBackgroundImageByTime(time: LocalTime): Int =
            when (time.hour) {
                in 6..18 -> R.drawable.imageday             
                else -> R.drawable.imagenight
            }

Now I am trying to get the images loaded by days of the week at the above times.

My images are: monday_imageday, monday_imagenight, tuesday_imageday, tuesday_imagenight, etc... How can I get these images loaded from drawable folder programatically depends on the day, today. If today is Tuesday, it should load imageday and imagenight respectively.

I am struck here and someone please help.


Solution

  • If your minimun SDK is 26, you can use LocalDateTime.

    val dateTime = LocalDateTime.now()
    val dayOfWeek = dateTime.dayOfWeek
    val hour = dateTime.hour
    
    val image = when(dayOfWeek) {
        DayOfWeek.MONDAY -> if (hour in 6..18) R.drawable.monday_imageday else R.drawable.monday_imagenight
        DayOfWeek.TUESDAY -> if (hour in 6..18) R.drawable.tuesday_imageday else R.drawable.tuesday_imagenight
        DayOfWeek.WEDNESDAY -> if (hour in 6..18) R.drawable.wednesday_imageday else R.drawable.wednesday_imagenight
        DayOfWeek.THURSDAY -> if (hour in 6..18) R.drawable.thursday_imageday else R.drawable.thursday_imagenight
        DayOfWeek.FRIDAY -> if (hour in 6..18) R.drawable.friday_imageday else R.drawable.friday_imagenight
        DayOfWeek.SATURDAY -> if (hour in 6..18) R.drawable.saturday_imageday else R.drawable.saturday_imagenight
        DayOfWeek.SUNDAY -> if (hour in 6..18) R.drawable.sunday_imageday else R.drawable.sunday_imagenight
    }
    

    If your minimum SDK is under 26, you can use Calendar for backward compatibility.

    val calendar = Calendar.getInstance()
    val dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)
    val hour = calendar.get(Calendar.HOUR_OF_DAY)
    
    val image = when(dayOfWeek) {
        1 -> if (hour in 6..18) R.drawable.monday_imageday else R.drawable.monday_imagenight
        2 -> if (hour in 6..18) R.drawable.tuesday_imageday else R.drawable.tuesday_imagenight
        3 -> if (hour in 6..18) R.drawable.wednesday_imageday else R.drawable.wednesday_imagenight
        4 -> if (hour in 6..18) R.drawable.thursday_imageday else R.drawable.thursday_imagenight
        5 -> if (hour in 6..18) R.drawable.friday_imageday else R.drawable.friday_imagenight
        6 -> if (hour in 6..18) R.drawable.saturday_imageday else R.drawable.saturday_imagenight
        7 -> if (hour in 6..18) R.drawable.sunday_imageday else R.drawable.sunday_imagenight
        else -> throw IllegalStateException()
    }