I have 2 activities with action bar which has this code in its onCrate
method:
getActionBar().setDisplayHomeAsUpEnabled(true);
And here is the onOptionsItemSelected
:
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.icon:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
The first activity has a parent activity (configured in the manifest) the second one just opened from fragment (without parent fragment configured in the manifest). In the first activity, when I click the icon, the activity item.getItemId()
value is the same as android.R.id.icon
which then falls in the switch statement (case: Android.R.id.icon
). In the second activity those values are deferent. Why this is happening? I would like to fall in the case: Android.R.id.icon
in both activities.
Use this type of code
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(1, 1, 1, "Done").setIcon(R.drawable.img_done)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
menu.add(1, 2, 2, "Save").setIcon(R.drawable.img_save)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
// Write your code for the first button
break;
case 2:
// Write your code for the second button
break;
}
return true;
}
Instead of using android.R.id.icon
use android.R.id.home
Try this code:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
For more detail check this link
Try this:
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.icon: //where 'icon' would be your item ID from menu.xml.
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
you are using android.R.id.icon
that might be wrong. Instead of that you may want to use R.id.icon
.
There is a difference between both R.id.icon
and android.R.icon
files.
Also make sure that you are not using following import
import android.R;
It may lead you to unwanted results.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.