微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android – 完成后退按钮两次按下时的活动?

参见英文答案 > Leaving android app with back button13个
我正在创建一个应用程序,我需要完成活动,当用户两次按下后退按钮.这是我尝试的代码
@Override
public void onBackpressed() {
        super.onBackpressed();
        this.finish();
}

也试过这个

@Override
public boolean onKeyDown(int keyCode,KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
    finish();
}
return super.onKeyDown(keyCode,event);
}

这有助于我按下后退按钮完成活动.

请,我需要你的建议.提前致谢

解决方法

好的…这是一个更长但有效的方法来做到这一点……

1)在你的课堂上做一个全球可修复的…

private boolean backpressedToExitOnce = false;
private Toast toast = null;

2)然后实现onBackpressed这样的活动……

@Override
public void onBackpressed() {
    if (backpressedToExitOnce) {
        super.onBackpressed();
    } else {
        this.backpressedToExitOnce = true;
        showToast("Press again to exit");
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                backpressedToExitOnce = false;
            }
        },2000);
    }
}

3)使用这个技巧有效地处理这种吐司…

/**
 * Created to make sure that you toast doesn't show miltiple times,if user pressed back
 * button more than once. 
 * @param message Message to show on toast.
 */
private void showToast(String message) {
    if (this.toast == null) {
        // Create toast if found null,it would he the case of first call only
        this.toast = Toast.makeText(this,message,Toast.LENGTH_SHORT);

    } else if (this.toast.getView() == null) {
        // Toast not showing,so create new one
        this.toast = Toast.makeText(this,Toast.LENGTH_SHORT);

    } else {
        // Updating toast message is showing
        this.toast.setText(message);
    }

    // Showing toast finally
    this.toast.show();
}

4)当你的活动关闭时,用这个技巧隐藏吐司……

/**
 * Kill the toast if showing. Supposed to call from onPause() of activity.
 * So that toast also get removed as activity goes to background,to improve
 * better app experiance for user
 */
private void killToast() {
    if (this.toast != null) {
        this.toast.cancel();
    }
}

5)实现你onPause()这样,当活动进入后台时杀死吐司

@Override
protected void onPause() {
    killToast();
    super.onPause();
}

希望这会有所帮助……

原文地址:https://www.jb51.cc/android/313819.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐