如何在单击时返回上一个活动并单击两次如何退出应用程序?

时间:2017-01-07 13:41:20

标签: android navigation fragment

当我单击后退按钮时,它将移至上一个屏幕,当我点击两次时,它将退出我的应用程序。

我尝试了很多并且也提到了stackoverflow问题但是无法解决我的问题,所以我在这里提出了一个问题。

NAvigation.java

   @Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    }
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        return;
    }
    else {

        backButtonHandler();
        //   Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
    }

}


public void backButtonHandler() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            Navigation.this);
    // Setting Dialog Title
    alertDialog.setTitle("Leave application?");
    // Setting Dialog Message
    alertDialog.setMessage("Are you sure you want to leave the application?");
    // Setting Icon to Dialog
    alertDialog.setIcon(R.drawable.m_visit);
    // Setting Positive "Yes" Button
    alertDialog.setPositiveButton("YES",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
    // Setting Negative "NO" Button
    alertDialog.setNegativeButton("NO",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // Write your code here to invoke NO event
                    dialog.cancel();
                }
            });
    // Showing Alert Message
    alertDialog.show();
}

我试过这种方式,但这只是帮助我退出应用程序。

1 个答案:

答案 0 :(得分:0)

试试这个逻辑

private int clickCount = 0;
private long delay = 100;
Timer timer = new Timer();
@Override
public void onBackPressed() {
  if (clickCount == 2) {
    timer.cancel();
    //operations to be performed on double click
  } else {
    clickCount++;
    timer.schedule(new TimerTask() {
      @Override public void run() {
        getActivity().runOnUiThread(new Runnable() {
          @Override public void run() {
            clickCount = 0;
            //operations to be performed on single click
          }
        });
      }
    }, delay);
  }
}

delay字段

中点击之间设置所需的延迟