Nếu bạn muốn thoát khỏi ứng dụng của bạn từ Hoạt động thứ hai trực tiếp mà không đi đến Hoạt động đầu tiên sau đó thử code..` này
Trong Hoạt động thứ hai đặt này mã ..
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
setResult(RESULT_OK, new Intent().putExtra("EXIT", true));
finish();
}
}).create().show();
}
Và hoạt động đầu tiên của bạn Đặt mã này .....
public class FirstActivity extends AppCompatActivity {
Button next;
private final static int EXIT_CODE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
next = (Button) findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivityForResult(new Intent(FirstActivity.this, SecondActivity.class), EXIT_CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == EXIT_CODE) {
if (resultCode == RESULT_OK) {
if (data.getBooleanExtra("EXIT", true)) {
finish();
}
}
}
}
}
Nguồn
2017-08-30 07:48:06
Thay thế 'this.finish() 'với' super.onBackPressed(); '. – Fred
thay vì 'this.finish()' thay vì gọi 'NavUtils.navigateUpFromSameTask (this);' để quay lại màn hình/hoạt động trước –