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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/android/313819.html

猜你在找的Android相关文章