I am new to kotlin and android studio and i am trying to have the day displayed in a text view. My problme is that only the number 1 to 7 is displayed acording to the current day but not the name of the day what do i have to change to fix this?
val day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fun dayOfWeek() {
val day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
println(
when (day) {
1 -> "Sunday"
2 -> "Monday"
3 -> "Tuesday"
4 -> "Wednesday"
5 -> "Thursday"
6 -> "Friday"
7 -> "Saturday"
else -> "Time has stopped"
}
)
}
tag = findViewById(R.id.Tag)
tag.text = day.toString()
CodePudding user response:
In your code, day
is an Int property.
You have created a function called dayOfWeek()
that you never call so that code never runs.
When you do tag.text = day.toString()
, it is looking at the day
property, not the day
variable inside your function. It is usually a bad idea to name a variable the same thing as some property in the same class because it makes the code confusing to read. But that doesn't matter either way in this case because both of them are Ints.
In your dayOfWeek()
function, you are using a when
expression to covert day
to a String, but you are just printing it. You are not storing it in a variable such that it can be used for anything else, like setting it on a TextView.
You can make your function return a String, and use it that way. I would also move your function outside the onCreate()
function. It is unusual to create a function inside another function for this kind of task.
val day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
tag = findViewById(R.id.Tag)
tag.text = getDayOfWeekText()
}
fun getDayOfWeekText() {
return when (day) {
1 -> "Sunday"
2 -> "Monday"
3 -> "Tuesday"
4 -> "Wednesday"
5 -> "Thursday"
6 -> "Friday"
7 -> "Saturday"
else -> "Time has stopped"
}
}
Or to do this the easy way, and with proper language support:
tag.setText(DateTimeFormatter.ofPattern("EEEE").format(LocalDate.now()))