2016-02-10 184 views
-2

我想在用戶單擊此活動中的退出Button時發出提醒。這怎麼能實現?按下退出按鈕時的提示

public class MainActivity extends Activity { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.mainactivity); 
     addListenerOnButton(); 
    } 

    public void addListenerOnButton() { 

     final Context context = this; 

     Button button1 = (Button)findViewById(R.id.button1); 
     Button button2 = (Button)findViewById(R.id.button2); 
     Button exit = (Button) findViewById(R.id.button4); 

     button1.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 

       Intent intent = new Intent(context, A.class); 
       startActivity(intent); 

      } 

     }); 
     button2.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 

       Intent intent = new Intent(context, B.class); 
       startActivity(intent); 

      } 

     }); 
     exit.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       moveTaskToBack(true); 
     }); 


    } 
    public void onBackPressed() { 
     new AlertDialog.Builder(this) 
       .setMessage("Are You Sure?") 
       .setCancelable(false) 
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
         MainActivity.this.finish(); 
        } 
       }) 
       .setNegativeButton("No", null) 
       .show(); 
    } 

    @Override public boolean onCreateOptionsMenu(Menu menu) { 
     return true; 
    } 

} 
+0

基本知識似乎都在您的代碼中。嘗試瞭解你做了什麼,試驗一下,你會得到你的結果。 – AlbAtNf

+0

完全同意@AlbAtNf,看看'onBackPressed()'下面的代碼那裏你創建一個alertdialog,用它作爲你的退出按鈕。 – Strider

+0

如果你想得到更明確的答案,你可以讓你的問題更具體 – jclozano

回答

0

創建一個名爲方法:exitDialog()這樣的:

public void exitDialog() { 
    new AlertDialog.Builder(this) 
      .setMessage("Are You Sure?") 
      .setCancelable(false) 
      .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        MainActivity.this.finish(); 
       } 
      }) 
      .setNegativeButton("No", null) 
      .show(); 
} 

比你onBackPressed()方法使用它,你的退出按鈕,如:

public void onBackPressed() { 
    exitDialog(); 
    super.onBackPressed(); 
} 

exit.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View v) { 
     exitDialog(); 
}); 
0

只需調用你的按鈕clicklistener你的onBackPressed()方法!

而且當你按下後退鍵物理按鈕時,你會得到相同的警報!

exit_button.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 

      onBackPressed(); 

     } 
    });