微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android – 如何检测是否按下了向上按钮

在我的活动中,操作栏仅显示左箭头和活动的标题.

当我按向左箭头时,活动将返回到上一个活动,但在onKeyUp,OnkeyDown和OnBackpressed方法中没有注册任何事件.

但是当我按下手机上的Back键(在底部)时,活动将返回到前一个,并且onKeyUp,OnKeyDown和OnBackpressed上的所有方法都会注册一个事件(在logcat中).

如何捕获左箭头(我认为它被称为UP按钮)?

我需要捕获密钥的原因是在onPause方法中知道活动是由用户而不是系统销毁的(例如,如果用户切换到另一个活动).

通过进一步研究他的问题我发现UP按钮给出了一个由onoptionsItemSelected方法捕获的事件,因为菜单上没有其他按钮,我知道它就是这个按钮.

解决方法

http://developer.android.com/guide/topics/ui/actionbar.html#Handling

处理对操作项的点击

用户按下某个动作时,系统将调用您的活动的onoptionsItemSelected()方法.使用传递给此方法的MenuItem,您可以通过调用getItemId()来识别该操作.这将返回标记的id属性提供的唯一ID,以便您可以执行相应的操作.例如:

@Override 
public boolean onoptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items 
    switch (item.getItemId()) {


        case android.R.id.home:
            onUpButtonpressed(); 
            return true; 



        case R.id.action_search:
            openSearch(); 
            return true; 
        case R.id.action_compose:
            composeMessage(); 
            return true; 
        default: 
            return super.onoptionsItemSelected(item);
    } 
}

Note: If you inflate menu items from a fragment,via the Fragment
class’s onCreateOptionsMenu() callback,the system calls
onoptionsItemSelected() for that fragment when the user selects one of
those items. However,the activity gets a chance to handle the event
first,so the system first calls onoptionsItemSelected() on the
activity,before calling the same callback for the fragment. To ensure
that any fragments in the activity also have a chance to handle the
callback,always pass the call to the superclass as the default
behavior instead of returning false when you do not handle the item.

要将应用程序图标启用为向上按钮,请调用setdisplayHomeAsUpEnabled().例如:

@Override 
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_details);

    ActionBar actionBar = getSupportActionBar();
    actionBar.setdisplayHomeAsUpEnabled(true);
    ... 
}

原文地址:https://www.jb51.cc/android/318398.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐