사용자가 Android 활동을 종료할지 확인하는 대화 상자를 표시하는 방법은 무엇입니까?
저는 "종료하시겠습니까?"라는 메시지를 보여주려고 노력했습니다.사용자가 활동을 종료하려고 할 때 대화 상자 유형.
하지만 적절한 API 후크를 찾을 수 없습니다.Activity.onUserLeaveHint()
처음에는 유망해 보였지만, 활동이 끝나는 것을 막을 방법을 찾을 수 없습니다.
Android 2.0+에서 이는 다음과 같습니다.
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
이전 버전에서는 다음과 같습니다.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if(keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.quit)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
YourClass.this.finish();
}
})
.setNegativeButton(R.string.no, null)
.show();
return true;
}
else {
return super.onKeyDown(keyCode, event);
}
}
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ExampleActivity.super.onBackPressed();
}
})
.setNegativeButton("No", null)
.show();
}
@user919216 코드를 수정하여 WebView와 호환되도록 했습니다.
@Override
public void onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
대화 상자를 종료하는 것보다 뒤로 단추를 두 번 눌러 종료하고 싶습니다.
이 솔루션에서는 처음 돌아갈 때 건배사를 보여주며, 다른 백프레스를 하면 앱이 닫힐 것이라고 경고합니다.이 예에서는 4초 미만입니다.
private Toast toast;
private long lastBackPressTime = 0;
@Override
public void onBackPressed() {
if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
toast = Toast.makeText(this, "Press back again to close this app", 4000);
toast.show();
this.lastBackPressTime = System.currentTimeMillis();
} else {
if (toast != null) {
toast.cancel();
}
super.onBackPressed();
}
}
토큰 출처: http://www.androiduipatterns.com/2011/03/back-button-behavior.html
"뒤로" 호출이 앱을 종료할지 또는 사용자를 다른 활동으로 데려갈지 확신할 수 없는 경우, 위의 답변을 체크로 묶어서 TaskRoot()로 처리할 수 있습니다.기본 활동을 백스택에 여러 번 추가할 수 있거나 백스택 기록을 조작하는 경우 이 문제가 발생할 수 있습니다.
if(isTaskRoot()) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
YourActivity.super.onBackPressed;
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
super.onBackPressed();
}
중국에서 대부분의 앱은 "두 번 클릭"으로 종료를 확인합니다.
boolean doubleBackToExitPressedOnce = false;
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
람다 사용:
new AlertDialog.Builder(this).setMessage(getString(R.string.exit_msg))
.setTitle(getString(R.string.info))
.setPositiveButton(getString(R.string.yes), (arg0, arg1) -> {
moveTaskToBack(true);
finish();
})
.setNegativeButton(getString(R.string.no), (arg0, arg1) -> {
})
.show();
또한 Gradle에서 Java 8을 지원하도록 레벨 언어를 설정해야 합니다.빌드:
compileOptions {
targetCompatibility 1.8
sourceCompatibility 1.8
}
첫 번째 제거super.onBackPressed();
부터onbackPressed()
코드 이하의 메서드:
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
Just put this code in your first activity
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
drawerLayout.closeDrawer(GravityCompat.END);
}
else {
// if your using fragment then you can do this way
int fragments = getSupportFragmentManager().getBackStackEntryCount();
if (fragments == 1) {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", null)
.show();
} else {
if (getFragmentManager().getBackStackEntryCount() > 1) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
}
저는 @GLEE 접근 방식을 좋아하고 아래와 같은 fragment와 함께 사용하는 것을 좋아합니다.
@Override
public void onBackPressed() {
if(isTaskRoot()) {
new ExitDialogFragment().show(getSupportFragmentManager(), null);
} else {
super.onBackPressed();
}
}
조각을 사용한 대화 상자:
public class ExitDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.exit_question)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getActivity().finish();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getDialog().cancel();
}
})
.create();
}
}
또 다른 대안은 첫 번째 백 프레스에 Snackbar
/ 키를 다시 눌러 종료할 것을 요청하는 화면을 표시하는 것입니다. 이 화면은 다음 화면을 표시하는 것보다 훨씬 덜 거슬립니다.AlertDialog
사용자가 앱을 종료할지 여부를 확인합니다.
를 사용하여 몇 줄의 코드로 이 작업을 수행할 수 있습니다.유사한 동작을 보여주는 GIF의 예.
우선 응용프로그램에 종속성을 추가합니다.
dependencies {
implementation 'com.github.kaushikthedeveloper:double-back-press:0.0.1'
}
그런 다음 활동에서 필요한 행동을 구현합니다.
// set the Toast to be shown on FirstBackPress (ToastDisplay - builtin template)
// can be replaced by custom action (new FirstBackPressAction{...})
FirstBackPressAction firstBackPressAction = new ToastDisplay().standard(this);
// set the Action on DoubleBackPress
DoubleBackPressAction doubleBackPressAction = new DoubleBackPressAction() {
@Override
public void actionCall() {
// TODO : Exit the application
finish();
System.exit(0);
}
};
// setup DoubleBackPress behaviour : close the current Activity
DoubleBackPress doubleBackPress = new DoubleBackPress()
.withDoublePressDuration(3000) // msec - wait for second back press
.withFirstBackPressAction(firstBackPressAction)
.withDoubleBackPressAction(doubleBackPressAction);
마지막으로, 이것을 백프레스의 동작으로 설정합니다.
@Override
public void onBackPressed() {
doubleBackPress.onBackPressed();
}
언급URL : https://stackoverflow.com/questions/2257963/how-to-show-a-dialog-to-confirm-that-the-user-wishes-to-exit-an-android-activity
'programing' 카테고리의 다른 글
스위프트의 if Let은 어떻게 평가됩니까? (0) | 2023.08.17 |
---|---|
현재 색상에 따라 반대 색상을 생성하려면 어떻게 해야 합니까? (0) | 2023.08.17 |
jQueryUniform 라이브러리를 사용하여 확인란을 선택 취소하는 방법 (0) | 2023.08.17 |
dataType jsonp와 JSON의 차이 (0) | 2023.08.17 |
옵션 Bool 값 확인 (0) | 2023.08.17 |