为什么onBack pressed()不会被调用? [英] Why is onBackPressed() not being called?
问题描述
我试图重写onBack pressed()。然而,它出现时我点击操作栏中的后退按钮无法察觉。
I am attempting to override onBackPressed(). However it appears to not detect when I click the back button in the action bar.
目前,我有这个code:
I currently have this code:
@Override
public void onBackPressed() {
Log.i("DATA", "Hit onBackPressed()");
super.onBackPressed();
}
日志信息不会出现在LogCat中。我知道,这个日志语句的工作,因为它是从,它在LogCat中显示不同的信息的另一种方法复制。
The log message never appears in the LogCat. I know that this log statement works because it is copied from another method with a different message that DOES display in the LogCat.
我已经寻找答案,我一直在使用onKeyDown和检测它是否被点击返回按钮,但我仍然有同样的问题尝试。
关于该项目的信息:
I have searched for answers, and I have tried using onKeyDown and detecting if it is the BACK button being clicked but I still have the same issue. Information about the project:
- Android的工作室0.9.3
- 方法位于空白活动
- 目标SDK 21
- 最小SDK 15
- 测试设备是三星Galaxy 5(而不是仿真器)
任何帮助将大大AP preciated !!
Any help would be greatly appreciated!!
编辑:
这是我的工作code的副本(这是测试code这样的活动名称不是描述性的):
This is a copy of my working code (this is test code so the activity name is not descriptive):
public class MainActivity2 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
getActionBar().setDisplayHomeAsUpEnabled(true);//Displays the back button
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main_activity2, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Log.i("DATA", "Hit Actionbar Back Button");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
消息打动作条后退按钮现在出现在LogCat中。
The message "Hit Actionbar Back Button" now appears in the LogCat.
推荐答案
onBack pressed()
当用户点击一个硬件后退按钮被调用(或向上导航栏中的按钮),而不是在动作栏按钮。对于这一项,你需要重写 onOptionsItemSelected()
方法。例如:
onBackPressed()
is invoked when user clicks on a hardware back button (or on the 'up' button in the navigation bar), not the button in the action bar. For this one you need to override onOptionsItemSelected()
method. Example:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// click on 'up' button in the action bar, handle it here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
这篇关于为什么onBack pressed()不会被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!