我想在用户点击此活动中的退出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 :(得分: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();
});
答案 1 :(得分:0)
只需调用你的按钮clicklistener你的onBackPressed()方法!
当您按下后退键物理按钮时,您会得到相同的警报!!!
exit_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});