gpt4 book ai didi

android - 如何在 Kotlin 中使用 switch-case 调用 Activity ?

转载 作者:行者123 更新时间:2023-11-30 04:58:44 28 4
gpt4 key购买 nike

如何在 Kotlin 中使用 switch-case 调用 Activity ?我想在 Kotlin 上使用 switch-case 结构,如下图所示。(Java 代码)

public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
break;
case R.id.navigation_adminword:
Intent a = new Intent(activity_callender.this,Words_List.class);
startActivity(a);
onStop();
break;
case R.id.navigation_myword:
Intent b = new Intent(activity_callender.this,SaveWords.class);
startActivity(b);
onStop();
break;
case R.id.navigation_profil:
Intent c = new Intent(activity_callender.this,UsersActivity.class);
startActivity(c);
onStop();
break;
}
return false;
}

最佳答案

你不能,因为 Java switch 在 Kotlin 中不可用,使用 when 甚至 if case...

fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.getItemId()) {
R.id.navigation_home -> // do something...
R.id.navigation_adminword -> {
val a = Intent(this@activity_callender, Words_List::class.java)
startActivity(a)
onStop() // this method is called automatically, it is no necessary call it manually
}
R.id.navigation_myword -> {
val b = Intent(this@activity_callender, SaveWords::class.java)
startActivity(b)
onStop() // this method is called automatically, it is no necessary call it manually
}
R.id.navigation_profil -> {
val c = Intent(this@activity_callender, UsersActivity::class.java)
startActivity(c)
onStop() // this method is called automatically, it is no necessary call it manually
}
else -> {
// else case would be the default switch case
}
}
return false
}

实际上你可以用when做更多的事情,比如返回一个值,然后把它赋值给一个变量,等等...

https://kotlinlang.org/docs/reference/control-flow.html#when-expression

关于android - 如何在 Kotlin 中使用 switch-case 调用 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58646127/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com