java 没有调用 Android onBackPressed()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39532594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:27:02  来源:igfitidea点击:

Android onBackPressed() is not being called?

javaandroidandroid-activityoverridingback

提问by Steve2955

in my MainActivity, which extends from AppCompatActivity, I want to override the onBackPressed method like so:

在从 AppCompatActivity 扩展的 MainActivity 中,我想像这样覆盖 onBackPressed 方法:

@Override
public void onBackPressed() {
    Log.d("MainActivity","onBackPressed");
    Toast.makeText(getApplicationContext(),"onBackPressed",Toast.LENGTH_SHORT).show();
}

but onBackPressed does not get called. How ever if I do not override onBackPressed, the application closes, when I press the backbutton and if I do override it it doesn't.

但 onBackPressed 不会被调用。如果我不覆盖 onBackPressed,应用程序将关闭,当我按下后退按钮时,如果我覆盖它,则不会。

The rest of my activity looks like this:

我的其余活动如下所示:

public class MainActivity extends AppCompatActivity {

private Toolbar toolbar;
private Drawer drawer;
private FloatingActionButton fab_test;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    fab_test = (FloatingActionButton) findViewById(R.id.fab_test);
    fab_test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplicationContext(),"FAB Test pressed",Toast.LENGTH_SHORT).show();
        }
    });

    buildDrawer();

    getSupportFragmentManager().beginTransaction().add(R.id.fragmentContainer,page).commit();
}

@Override
public void onBackPressed() {
    Log.d("MainActivity","onBackPressed");
    Toast.makeText(getApplicationContext(),"onBackPressed",Toast.LENGTH_SHORT).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu, menu);      
    return true;
}
}

EDIT: I'm talking about the hardware-backbutton(not the actionbar one)

编辑:我说的是硬件后退按钮(不是操作栏一个)

回答by Opiatefuchs

This question is already answered, but I feel to clear something here in this topic. Most comments and answeres point out to use super.onBackPressed()and that this is the cause of the not working method onBackPressed(). But that is not correct and important to let other beginners know. The method onBackPressed()does not need to use super.onBackPressed(). onBackPressed()also works if somebody, for example, comment super.onBackPressed()out.

这个问题已经回答了,但我觉得在这个主题中澄清了一些东西。大多数评论和回答都指出要使用super.onBackPressed(),这是导致方法无效的原因onBackPressed()。但让其他初学者知道这是不正确和重要的。该方法onBackPressed()不需要使用super.onBackPressed(). onBackPressed()例如,如果有人注释掉也super.onBackPressed()可以使用。

As the questionier has written, he won′t use super.onBackPressed()because it will close the activity. So, the cause of this why it isn′t working, could be seperated into three possible causes:

正如提问者所写,他不会使用,super.onBackPressed()因为它会关闭活动。因此,导致它无法正常工作的原因可以分为三个可能的原因:

  1. The Log doesn′t work because of a wrong filter in the logcat console
  2. The Toast dosn′t work because of the wrong passed context
  3. The OS is implemented wrong by the supplier.
  1. 由于 logcat 控制台中的过滤器错误,日志不起作用
  2. 由于传递的上下文错误,Toast 不起作用
  3. 供应商实施的操作系统错误。

Usually, the toast works by passing the correct context. In the case of questioner, simply passing this.

通常,吐司通过传递正确的上下文来工作。在提问者的情况下,只需通过this

@Override
public void onBackPressed() {
    Log.d("MainActivity","onBackPressed");
    Toast.makeText(this,"onBackPressed",Toast.LENGTH_SHORT).show();
}

For the Log, simply set the correct filter on logcat.

对于日志,只需在 logcat 上设置正确的过滤器。

I don′t care if somebody give downvotes now, but it must be clear for other beginners, that super.onBackPressed()must not be used.

我不在乎现在是否有人给downvote,但对于其他初学者来说必须清楚,super.onBackPressed()不能使用。

Anyway, the use of onKeyDown()also is a solution.

不管怎样,使用onKeyDown()也是一种解决方法。

回答by BitByteDog

The onBackPressed()is a default action called from onKeyDown()in API < 5 and a default action called from onKeyUp()from API level 5 and up. If onKeyUp()does not call super.onKeyUp(), onBackPressed()will not be called.

onBackPressed()是从onKeyDown()API < 5 中调用的默认操作和onKeyUp()从 API 级别 5 及更高级别调用的默认操作。如果onKeyUp()不调用super.onKeyUp()onBackPressed()则不会被调用。

Documentation onKeyDown()

文档onKeyDown()

Documentation onKeyUp().

文档onKeyUp()

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    /*
     * without call to super onBackPress() will not be called when
     * keyCode == KeyEvent.KEYCODE_BACK
     */
    super.onKeyUp(keyCode, event);
}

Also another reason that onBackPressed()may not be called is because you are using the soft back button on the actionbar, it that case the following is needed:

另一个onBackPressed()可能不会被调用的原因是因为您正在使用操作栏上的软后退按钮,在这种情况下需要以下内容:

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

回答by Saveen

You are missing, super.onBackPressed();

你不见了,super.onBackPressed();

@Override
public void onBackPressed() {
    super.onBackPressed();
}

or you can use

或者你可以使用

@Override  
public boolean onKeyDown(int keyCode, KeyEvent event)  
{  
     //replaces the default 'Back' button action  
     if(keyCode==KeyEvent.KEYCODE_BACK)   {  
// something here
            finish();
     }  
     return true;  
 }  

thanks

谢谢

回答by vijay

Just Remove super.onBackPressed() it will work

只需删除 super.onBackPressed() 即可

回答by Ahmed Esameddeen

make sure you are not calling onkeydown in your super view as it handles the back button clicking first.

确保您没有在超级视图中调用 onkeydown,因为它首先处理后退按钮单击。