android返回鍵退出提示的兩種方法

本文提供了兩種觸摸返回鍵提示退出的兩種方法

1.觸摸返回鍵彈出對話框

public void onBackPressed(){        //android 2.0以上的 <a target=_blank href="http://blog.csdn.net/u010717419/article/details/24481537">點擊解釋爲什麼</a>
        Toast.makeText(this, "你點擊了返回鍵", Toast.LENGTH_LONG).show();
        AlertDialog.Builder builder = new Builder(this);
        builder.setTitle("提示");
        builder.setMessage("確認要退出嗎");
        
        builder.setPositiveButton("確認", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		});
        builder.setNegativeButton("取消", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//不做任何動作
			}
		});
        
        builder.create().show();
     }
2.觸摸兩次返回鍵退出

private long currentBackPressedTime = 0;
	private static final int BACK_PRESSED_INTERVAL = 2000;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    public void onBackPressed(){
    	    //1.當前的獲取的毫秒數-預定值(0)肯定大於2s  //4.當下次再按時當前值跟賦予後的設定值比較
    	if(System.currentTimeMillis() - currentBackPressedTime > BACK_PRESSED_INTERVAL){
    		//2.把當前的毫秒數賦予預定值
    		currentBackPressedTime = System.currentTimeMillis() ; 
    		//3.彈出框
    		Toast.makeText(this, "再按一次退出", 0).show();
    	}else{
    		//若當前值-設定值<2s 則執行:
    		finish();
    	}
    }



發佈了23 篇原創文章 · 獲贊 4 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章