单击应用程序图标不会触发 onOptionsItemSelected()
我目前正在开发 Android 应用程序。我想使用操作栏中的应用程序图标导航到“主页”活动。我在 this 页面上读到,所需要做的就是添加onOptionsItemSelected
并查找 id android.R.id.home
。
这是我在 Activity 中实现的代码,我想按应用程序图标返回 HomeActivity
。
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
然而,什么也没有发生。调试时,我可以看到单击图标根本不会触发 onOptionsItemSelected()
。我必须在某个地方对图标做一些事情吗?到目前为止,这都是默认的,只是在 AndroidManifest.xml
中
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
I'm currently working on an Android app. I would like to use the app icon in the action bar to navigate to the "home" activity. I read on this page that all that needs to be done is to add an onOptionsItemSelected
and look for the id android.R.id.home
.
This is the code that I have implemented in my activity where I want to press the app icon to return to HomeActivity
.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
However, nothing happens. When debugging, I can see that clicking the icon doesn't trigger the onOptionsItemSelected()
at all. Do I have to do something with the icon somewhere? As of now, it's all default, just this in the AndroidManifest.xml
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于面向 API 级别 14 及以上版本的软件包,您需要通过调用
setHomeButtonEnabled()
在 onCreate 中,添加以下内容:
For packages targetting API level 14 onwards, you need to enable the home button by calling
setHomeButtonEnabled()
In your onCreate, add the following:
如果您使用 Android 新的 support-actionbar (AppCompat)您需要拨打这两个电话。
If you use Android new support-actionbar (AppCompat) you need to make both calls.
我不知道我们是否有同样的问题。
但是,我曾经遇到过这个问题,现在已经解决了..
您是否添加了
HomeActivity ?
这是错误的..
您应该将该代码放在您的第二个活动中..
因为你的主页按钮在第二个活动上,而不是主页活动
希望这对你有帮助
i dont know if we have the same problem.
but, i was on that problem and now solved..
do you add
in HomeActivity ?
this is false..
you should put that code on your secondActivity..
because your home button on secondActivity, not HomeActivity
hope this helps you