Android案例声明帮助

use*_*940 5 android android-layout

我试图让我的case语句根据按下的按钮打开另一个类.我得到这个工作正常一个按钮,但我不确定如何继续两个按钮.

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

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;

    }

}
Run Code Online (Sandbox Code Playgroud)

这给出了一个错误,因为我正在重用本地变量(i) - 如果有人能让我知道如何正确地做这个,那将非常感激.

Vic*_*ian 3

i您可以在 switch 语句之前声明变量。i如果您计划在 switch 语句之后使用变量,这比“范围界定”尤其可取:

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'
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您不处理默认情况,则更容易出错。至少确保初始化并检查 i 。 (2认同)