[英]understanding onOptionsItemSelected
我有2个带有操作栏的活动,其onCrate
方法中包含以下代码:
getActionBar().setDisplayHomeAsUpEnabled(true);
这是onOptionsItemSelected
:
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.icon:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
第一个活动具有父活动(在清单中配置),第二个活动刚刚从片段打开(没有在清单中配置父片段)。 在第一个活动中,当我单击图标时,活动item.getItemId()
值与android.R.id.icon
相同,后者落入switch语句(例如: Android.R.id.icon
)。 在第二个活动中,这些值是不同的。 为什么会这样? 我想在这两种活动中都是Android.R.id.icon
。
使用这种类型的代码
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;
}
而不是使用android.R.id.icon
使用android.R.id.home
试试这段代码:
@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);
}
有关详细信息,请查看此链接
尝试这个:
@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);
}
}
你使用的android.R.id.icon
可能是错的。 而不是你可能想要使用R.id.icon
。
R.id.icon
和android.R.icon
文件之间存在差异。
还要确保您没有使用以下导入
import android.R;
它可能会导致不必要的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.