Search code examples
javaandroidkotlinandroid-viewbinding

whats a simple way of inputting days of the week in a view?


So I have 3 text views to show the forecast of the next 3 days. I used view binding to bind the views but I feel there's a much simpler way of writing this but I can't think of a solution. How could I iterate through the days of the week and set the text view accordingly?

'''
// getting day of the week
private val dayOfWeek: DayOfWeek = LocalDate.now().dayOfWeek
// getting day of week as int value
private val dayNum: Int = dayOfWeek.value

'''

     ''' // 1 = monday etc

      private fun forecastDays() {


        when (dayNum){
            // forecast of next three days
            1 -> {
                binding.tvDay1.text = "Tuesday"
                binding.tvDay2.text = "Wednesday"
                binding.tvDay3.text = "Thursday"
            }
            2 -> {
                binding.tvDay1.text = "Wednesday"
                binding.tvDay2.text = "Thursday"
                binding.tvDay3.text = "Friday"
            }
            3 -> {
                binding.tvDay1.text = "Thursday"
                binding.tvDay2.text = "Friday"
                binding.tvDay3.text = "Saturday"
            }
            4 -> {
                binding.tvDay1.text = "Friday"
                binding.tvDay2.text = "Saturday"
                binding.tvDay3.text = "Sunday"
            }
          .. etc

'''


Solution

  • You can probably do it with DateFormatter i guess . Here is the one other approach with map. u can make daysMap as a constant.

    val daysMap = mapOf(
        1 to "Sunday", 2 to "Monday", 3 to "Tuesday", 4 to "Wednesday", 5 to "Thursday", 6 to "Friday", 7 to "Saturday"
    )
    val dayOfWeek: DayOfWeek = LocalDate.now().dayOfWeek
    val dayNum: Int = dayOfWeek.value
    binding.tvDay1.text = daysMap[(dayNum + 1) % 7]
    binding.tvDay2.text = daysMap[(dayNum + 2) % 7]
    binding.tvDay3.text = daysMap[(dayNum + 3) % 7]