安卓:正确的方法使用onBack pressed() [英] Android: Proper Way to use onBackPressed()

查看:258
本文介绍了安卓:正确的方法使用onBack pressed()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一张code,会给用户一个提示,询问他们preSS回来,如果他们想退出。目前,我有我的code工作的程度,但我知道它是写得不好,我想有一个更好的方式来做到这一点。任何建议将是有益的!

code:

 公共无效onBack pressed(){
    回到preSS =(回preSS + 1);
    Toast.makeText(getApplicationContext(),再度回到preSS以退出,Toast.LENGTH_SHORT).show();

    如果(背面preSS→1){
        this.finish();
    }
}
 

解决方案

我想实现一个对话框,询问用户是否想退出,然后调用pssed super.onBack $ P $(),如果他们做到了。

  @覆盖
公共无效onBack pressed(){
    新AlertDialog.Builder(本)
        .setTitle(真的退出?)
        .setMessage(你确定要退出吗?)
        .setNegativeButton(android.R.string.no,空)
        .setPositiveButton(android.R.string.yes,新OnClickListener(){

            公共无效的onClick(DialogInterface为arg0,INT ARG1){
                WelcomeActivity.super.onBack pressed();
            }
        })创建()显示()。
}
 

在上面的例子中,你需要与你的活动的名称替换WelcomeActivity。

I wrote a piece of code that will give the user a prompt asking them to press back again if they would like to exit. I currently have my code working to an extent but I know it is written poorly and I assume there is a better way to do it. Any suggestions would be helpful!

Code:

public void onBackPressed(){
    backpress = (backpress + 1);
    Toast.makeText(getApplicationContext(), " Press Back again to Exit ", Toast.LENGTH_SHORT).show();

    if (backpress>1) {
        this.finish();
    }
}

解决方案

I would implement a dialog asking the user if they wanted to exit and then call super.onBackPressed() if they did.

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
        .setTitle("Really Exit?")
        .setMessage("Are you sure you want to exit?")
        .setNegativeButton(android.R.string.no, null)
        .setPositiveButton(android.R.string.yes, new OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
                WelcomeActivity.super.onBackPressed();
            }
        }).create().show();
}

In the above example, you'll need to replace WelcomeActivity with the name of your activity.

这篇关于安卓:正确的方法使用onBack pressed()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆