Wie verwerfe ich ein DialogFragment, wenn ich außerhalb des Dialogs drücke?
Lesezeit: 3 Minuten
Sohle, einzig, alleinig
Ich verwende eine DialogFragment, und obwohl ich ein Bild erfolgreich so eingestellt habe, dass es den Dialog schließt (d. h. schließt), wenn er gedrückt wird, fällt es mir schwer, den Dialog zu schließen, wenn der Benutzer irgendwo außerhalb davon klickt, so wie es bei normalen Dialogen funktioniert. Ich dachte, es gäbe eine Art
dialogFragment.setCanceledOnTouchOutside(true);
anrufen, aber ich sehe das nicht in der Dokumentation.
Geht das mit DialogFragment überhaupt? Oder suche ich an den falschen Stellen? Ich habe versucht, Touch-Ereignisse in der Aktivität „Eltern“ abzufangen, aber abgesehen davon, dass ich kein Touch-Ereignis erhalten habe, schien es mir nicht richtig zu sein.
In diesem Beispiel getDialog().setCanceledOnTouchOutside(true); не сработало, сработало getDialog().dismiss();
– Максим Фомичёв
22. März 2018 um 13:53 Uhr
@МаксимФомичёв, в первом случае происходит установка свойства диалога, что его можно закрывать нажатием снаружи. Во втором случае вы сами программно закрываете диалог.
– CoolMind
17. April 2019 um 8:04 Uhr
/** The system calls this only when creating the layout in a dialog. */
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// The only reason you might override this method when using onCreateView() is
// to modify any dialog characteristics. For example, the dialog includes a
// title by default, but your custom layout might not need it. So here you can
// remove the dialog title, but you must call the superclass to get the Dialog.
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCanceledOnTouchOutside(true);
return dialog;
}
das hat bei mir nicht funktioniert. Ich musste anrufen setCanceledOnTouchOutside in onCreateView gemäß @Apurv. Ich sollte erwähnen, dass ich angerufen habe setCanceledOnTouchOutside(false)
– Kimbaud
23. Oktober 2016 um 7:46 Uhr
Viele Antworten hier, aber die App stürzt ab, wenn der Dialog geöffnet wird. Schreiben getDialog().setCanceledOnTouchOutside(true); Innerhalb onCreateView hat nicht funktioniert und meine App zum Absturz gebracht.
(Ich benutze AppCompatActivity als meine BaseActivity und android.app.DialogFragment als mein Fragment).
Was funktioniert, ist eine der beiden folgenden Zeilen:
getDialog().setCanceledOnTouchOutside(true);
ODER
this.getDialog().setCanceledOnTouchOutside(true);
Innerhalb onActivityCreated wie
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//getDialog().getWindow().getAttributes().windowAnimations = R.style.DialogAnimationZoom;
//getDialog().getWindow().setDimAmount(0.85f);
getDialog().setCanceledOnTouchOutside(true);//See here is the code
}