2016-01-29 63 views
-1
@Override 
    public void onBackPressed() { 


      Log.d("back button", "back button pressed"); 
      AlertDialog.Builder ad1=new AlertDialog.Builder(getActivity()); 
      ad1.setMessage("Are you sure you want to exit? "); 
      ad1.setCancelable(false); 

      ad1.setPositiveButton("YES", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface arg0, int arg1) { 
        Intent i = new Intent(getActivity(), LoginActivity.class); 
        startActivity(i); 

       } 
      }); 


      ad1.setNegativeButton("NO", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface arg0, int arg1) { 

        Intent i = new Intent(getActivity(), FrndsearchFragment.class); 
        startActivity(i); 

       } 
      }); 


      AlertDialog alert=ad1.create(); 
      alert.show(); 

     } 

利用我得到的錯誤在@Override代碼,我寫的super.onBackPressed我得到onBackPressed在super.onBackPressed有可能在回壓法的警告對話框中片段

+0

嗨,朋友,你可以發佈完整的方法onBackPressed嗎? –

+0

[在Java按鈕中調用AlertDialog.Builder時返回按鈕被按下]的可能重複(http://stackoverflow.com/questions/21615358/calling-alertdialog-builder-in-java-for-android-fragment-when -back-button-is-pre) –

+0

嗨朋友, 無法在片段中添加onBackPressed方法,您應該在Activity中處理此方法,檢查當前片段並通過TAG處理(當您替換片段時,添加TAG) –

回答

0

是的,你可以通過重寫onKeyDown方法來做同樣的事情。

@Override 
public boolean onKeyDown(int keyCode, KeyEvent event) { 
    if(keyCode == KeyEvent.KEYCODE_BACK) { 
     AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setCancelable(false); 
     builder.setTitle("Exit"); 
     builder.setMessage("Do you want to exit the application?"); 
     builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.dismiss(); 
       exit(); 
      } 
     }); 
     builder.setNegativeButton("No", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.dismiss(); 
      } 
     }); 
     AlertDialog dialog = builder.create(); 
     dialog.show(); 
     return true; 
    } 
    return super.onKeyDown(keyCode, event); 
} 

private void exit() { 
    finish(); 
}