在我的活动中,操作栏仅显示左箭头和活动标题。
当我按下左箭头时,活动将返回上一个活动,但onKeyUp,OnkeyDown和OnBackPressed方法中没有注册任何事件。
但是当我按下手机上的Back键(在底部)时,活动会返回到前一个,并且onKeyUp,OnKeyDown和OnBackPressed上的所有方法都会注册一个事件(在logcat中)。
如何捕获左箭头(我认为它被称为UP按钮)?
我需要捕获密钥的原因是在onPause方法中知道活动是由用户而不是系统销毁的(例如,如果用户切换到另一个活动)。
通过进一步研究他的问题我发现UP按钮给出了一个由onOptionsItemSelected方法捕获的事件,因为菜单上没有其他按钮,我知道它就是这个按钮。
答案 0 :(得分:7)
请参阅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);
}
}
注意:如果您通过片段从片段中膨胀菜单项 class onCreateOptionsMenu()回调,系统调用 当用户选择其中一个时,该片段的onOptionsItemSelected() 那些物品。但是,活动有机会处理该事件 首先,系统首先调用onOptionsItemSelected() activity,在调用片段的相同回调之前。确保 活动中的任何片段也有机会处理 回调,始终将调用传递给超类作为默认值 当你不处理该项时,行为而不是返回false。
要将应用程序图标设置为向上按钮,请调用setDisplayHomeAsUpEnabled()。例如:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
...
}
答案 1 :(得分:2)
是的,你是对的,你可以检测onOptionsItemSelected方法中是否按下了向上按钮。这应该有效:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Do something here. This is the event fired when up button is pressed.
return true;
}
return super.onOptionsItemSelected(item);
}