在视图中输入一周中的天数的简单方法是什么?

smtd7mpg  于 2021-08-25  发布在  Java
关注(0)|答案(2)|浏览(338)

因此,我有3个文本视图来显示未来3天的预测。我使用视图绑定来绑定视图,但我觉得有一种更简单的方法来编写它,但我想不出解决方案。如何迭代一周中的几天并相应地设置文本视图?

'''
// 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

'''

piok6c0g

piok6c0g1#

你可以用它来做 DateFormatter 我想是吧。下面是另一种使用map的方法。你可以 daysMap 作为常数。

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]
iyfjxgzm

iyfjxgzm2#

dayofweek是一个枚举,这意味着您可以使用序号作为索引以数字形式获取dayofweek。

// getting day of the week
private val dayOfWeek: DayOfWeek = LocalDate.now().dayOfWeek
// ordinal
private val dayNum: Int = dayOfWeek.ordinal()
...
private fun forecastDays() {

    binding.tvDay1.text = DayOfWeek.values()[(dayNum + 1) % 7].name()
    binding.tvDay2.text = DayOfWeek.values()[(dayNum + 2) % 7].name()
    binding.tvDay3.text = DayOfWeek.values()[(dayNum + 3) % 7].name()
...

相关问题