[英]understanding onOptionsItemSelected
I have 2 activities with action bar which has this code in its onCrate
method: 我有2个带有操作栏的活动,其onCrate
方法中包含以下代码:
getActionBar().setDisplayHomeAsUpEnabled(true);
And here is the onOptionsItemSelected
: 这是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
). 在第一个活动中,当我单击图标时,活动item.getItemId()
值与android.R.id.icon
相同,后者落入switch语句(例如: 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. 我想在这两种活动中都是Android.R.id.icon
。
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
而不是使用android.R.id.icon
使用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);
}
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. 你使用的android.R.id.icon
可能是错的。 Instead of that you may want to use R.id.icon
. 而不是你可能想要使用R.id.icon
。
There is a difference between both R.id.icon
and android.R.icon
files. R.id.icon
和android.R.icon
文件之间存在差异。
Also make sure that you are not using following import 还要确保您没有使用以下导入
import android.R;
It may lead you to unwanted results. 它可能会导致不必要的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.