android menu does not work properly
in an android app , I use menus for an activity
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/logout"
android:title="Logout" />
<item
android:id="@+id/compose"
android:title="Compose" />
<item
android:id="@+id/refresh"
android:title="Refresh" />
</menu>
and in activity :
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.inboxmenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.logout:
SharedPreferences settings =getSharedPreferences("CASPreferences", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putString("uid", "");
prefEditor.putString("stdno", "");
prefEditor.putString("firstname", "");
prefEditor.putString("lastname", "");
prefEditor.putString("lastname", "");
prefEditor.commit();
Intent myIntent = new Intent(this, LoginActivity.class);
startActivity(myIntent);
return true;
case R.id.refresh:
Log.e("menu" , "refresh");
//Intent intent=new Intent(this,MainActivity.class);
startActivity(getIntent());
finish();
case R.id.compose:
开发者_JAVA技巧 Log.e("menu" , "compose");
Intent intent1=new Intent(this,ComposeActivity.class);
startActivity(intent1);
default:
return super.onOptionsItemSelected(item);
}
}
but when I click on refresh button , it goes to compose activity ! like as you clicked on compose.
why does this happen?
add break
to your switch statement, otherwise your code will continue into the third case
You haven`t added break; for each switch stmt. Please try and share the result.
Rewrite your switch
statement.
switch (item.getItemId()) {
case R.id.logout:
...
return true;
case R.id.refresh:
...
finish();
break; // <- Add this line
case R.id.compose:
...
break; // <- Add this line
default:
return super.onOptionsItemSelected(item);
}
Each case
block must be enclosed by break
.
The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
break
doesn't required in first case
block because flow interrupted by return
statement.
Reference: http://download.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
精彩评论