gpt4 book ai didi

Android case语句帮助

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:49:53 24 4
gpt4 key购买 nike

我试图让我的案例陈述根据按下的按钮打开一个不同的类。我在一个按钮上工作正常,但不确定如何处理两个按钮。

到目前为止,这是我的代码:

public void onClick(View v) {
switch (v.getId()) {
case R.id.about_button:
Intent i = new Intent(this, About.class);
startActivity(i);
break;
case R.id.reminderList_button:
Intent i = new Intent (this, ReminderListActivity.class);
startActivity(i);
break;

}

}

这会出错,因为我正在重用局部变量 (i) - 如果有人能告诉我如何正确执行此操作,我们将不胜感激。

最佳答案

您可以在 switch 语句之前声明变量 i。如果您计划在 switch 语句之后使用变量 i,这比“作用域”更可取:

public void onClick(View v) {
Intent i = null;
switch (v.getId()) {
case R.id.about_button:
i = new Intent(this, About.class);
break;
case R.id.reminderList_button:
i = new Intent (this, ReminderListActivity.class);
break;
}
startActivity(i);
...; // other statements using `i'
}

关于Android case语句帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4495220/

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