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);
    ... 
}

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...