开发者

Android case statement help

I'm trying to开发者_如何学C make my case statement open up a different class depending on what button is pressed. I got this working fine for one button but am unsure how to proceed for two buttons.

Heres my code so far:

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;

    }

}

This gives an error because I'm reusing the local variable (i) - if anyone could let me know how to do this properly it would be much appreciated.


You could declare the variable i before the switch statement. This is especially preferable to "scoping" if you plan to use the variable i after the switch statement:

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


Scope it.

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;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜