Class AlertDialog
- All Implemented Interfaces:
Accessible,Buildable,ConstraintTarget,ShortcutManager,Proxy
Alert dialogs have a heading, a body, an optional child widget, and one or multiple responses, each presented as a button.
Each response has a unique string ID, and a button label. Additionally, each response can be enabled or disabled, and can have a suggested or destructive appearance.
When one of the responses is activated, or the dialog is closed, the
AlertDialog::response signal will be emitted. This signal is
detailed, and the detail, as well as the response parameter will be set to
the ID of the activated response, or to the value of the
AlertDialog:close-response property if the dialog had been closed
without activating any of the responses.
Response buttons can be presented horizontally or vertically depending on available space.
When a response is activated, AdwAlertDialog is closed automatically.
An example of using an alert dialog:
AdwDialog *dialog;
dialog = adw_alert_dialog_new (_("Replace File?"), NULL);
adw_alert_dialog_format_body (ADW_ALERT_DIALOG (dialog),
_("A file named “%s” already exists. Do you want to replace it?"),
filename);
adw_alert_dialog_add_responses (ADW_ALERT_DIALOG (dialog),
"cancel", _("_Cancel"),
"replace", _("_Replace"),
NULL);
adw_alert_dialog_set_response_appearance (ADW_ALERT_DIALOG (dialog),
"replace",
ADW_RESPONSE_DESTRUCTIVE);
adw_alert_dialog_set_default_response (ADW_ALERT_DIALOG (dialog), "cancel");
adw_alert_dialog_set_close_response (ADW_ALERT_DIALOG (dialog), "cancel");
g_signal_connect (dialog, "response", G_CALLBACK (response_cb), self);
adw_dialog_present (dialog, parent);
Async API
AdwAlertDialog can also be used via the choose(org.gnome.gtk.Widget, org.gnome.gio.Cancellable, org.gnome.gio.AsyncReadyCallback) method.
This API follows the GIO async pattern, for example:
static void
dialog_cb (AdwAlertDialog *dialog,
GAsyncResult *result,
MyWindow *self)
{
const char *response = adw_alert_dialog_choose_finish (dialog, result);
// ...
}
static void
show_dialog (MyWindow *self)
{
AdwDialog *dialog;
dialog = adw_alert_dialog_new (_("Replace File?"), NULL);
adw_alert_dialog_format_body (ADW_ALERT_DIALOG (dialog),
_("A file named “%s” already exists. Do you want to replace it?"),
filename);
adw_alert_dialog_add_responses (ADW_ALERT_DIALOG (dialog),
"cancel", _("_Cancel"),
"replace", _("_Replace"),
NULL);
adw_alert_dialog_set_response_appearance (ADW_ALERT_DIALOG (dialog),
"replace",
ADW_RESPONSE_DESTRUCTIVE);
adw_alert_dialog_set_default_response (ADW_ALERT_DIALOG (dialog), "cancel");
adw_alert_dialog_set_close_response (ADW_ALERT_DIALOG (dialog), "cancel");
adw_alert_dialog_choose (ADW_ALERT_DIALOG (dialog), GTK_WIDGET (self),
NULL, (GAsyncReadyCallback) dialog_cb, self);
}
AdwAlertDialog as GtkBuildable
AdwAlertDialog supports adding responses in UI definitions by via the
<responses> element that may contain multiple <response> elements, each
representing a response.
Each of the <response> elements must have the id attribute specifying the
response ID. The contents of the element are used as the response label.
Response labels can be translated with the usual translatable, context
and comments attributes.
The <response> elements can also have enabled and/or appearance
attributes. See setResponseEnabled(java.lang.String, boolean) and
setResponseAppearance(java.lang.String, org.gnome.adw.ResponseAppearance) for details.
Example of an AdwAlertDialog UI definition:
<object class="AdwAlertDialog" id="dialog">
<property name="heading" translatable="yes">Save Changes?</property>
<property name="body" translatable="yes">Open documents contain unsaved changes. Changes which are not saved will be permanently lost.</property>
<property name="default-response">save</property>
<property name="close-response">cancel</property>
<signal name="response" handler="response_cb"/>
<responses>
<response id="cancel" translatable="yes">_Cancel</response>
<response id="discard" translatable="yes" appearance="destructive">_Discard</response>
<response id="save" translatable="yes" appearance="suggested" enabled="false">_Save</response>
</responses>
</object>
- Since:
- 1.5
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classstatic classAlertDialog.Builder<B extends AlertDialog.Builder<B>>Inner class implementing a builder pattern to construct a GObject with properties.static interfaceFunctional interface declaration of theResponseCallbackcallback.Nested classes/interfaces inherited from class org.gnome.adw.Dialog
Dialog.CloseAttemptCallback, Dialog.ClosedCallback, Dialog.DialogClassNested classes/interfaces inherited from class org.gnome.gtk.Widget
Widget.DestroyCallback, Widget.DirectionChangedCallback, Widget.HideCallback, Widget.KeynavFailedCallback, Widget.MapCallback, Widget.MnemonicActivateCallback, Widget.MoveFocusCallback, Widget.QueryTooltipCallback, Widget.RealizeCallback, Widget.ShowCallback, Widget.StateFlagsChangedCallback, Widget.UnmapCallback, Widget.UnrealizeCallback, Widget.Widget$Impl, Widget.WidgetClassNested classes/interfaces inherited from class org.gnome.gobject.InitiallyUnowned
InitiallyUnowned.InitiallyUnownedClassNested classes/interfaces inherited from class org.gnome.gobject.GObject
GObject.NotifyCallback, GObject.ObjectClassNested classes/interfaces inherited from interface org.gnome.gtk.Accessible
Accessible.Accessible$Impl, Accessible.AccessibleInterfaceNested classes/interfaces inherited from interface org.gnome.gtk.Buildable
Buildable.Buildable$Impl, Buildable.BuildableIfaceNested classes/interfaces inherited from interface org.gnome.gtk.ConstraintTarget
ConstraintTarget.ConstraintTarget$Impl, ConstraintTarget.ConstraintTargetInterfaceNested classes/interfaces inherited from interface org.gnome.gtk.ShortcutManager
ShortcutManager.ShortcutManager$Impl, ShortcutManager.ShortcutManagerInterface -
Constructor Summary
ConstructorsConstructorDescriptionCreates a new AlertDialog.AlertDialog(@Nullable String heading, @Nullable String body) Creates a newAdwAlertDialog.AlertDialog(MemorySegment address) Create a AlertDialog proxy instance for the provided memory address. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddResponse(String id, String label) Adds a response withidandlabeltoself.voidaddResponses(String firstId, Object... varargs) Adds multiple responses toself.protected AlertDialogasParent()Returns this instance as if it were its parent type.static AlertDialog.Builder<? extends AlertDialog.Builder> builder()AAlertDialog.Builderobject constructs aAlertDialogwith the specified properties.voidchoose(@Nullable Widget parent, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback) This function shows this AlertDialog to the user.chooseFinish(AsyncResult result) Finishes thechoose(org.gnome.gtk.Widget, org.gnome.gio.Cancellable, org.gnome.gio.AsyncReadyCallback)call and returns the response ID.voidemitResponse(@Nullable String detail, String response) Emits the "response" signal.voidformatBody(String format, Object... varargs) Sets the formatted body text ofself.voidformatBodyMarkup(String format, Object... varargs) Sets the formatted body text of this AlertDialog with Pango markup.voidformatHeading(String format, Object... varargs) Sets the formatted heading ofself.voidformatHeadingMarkup(String format, Object... varargs) Sets the formatted heading of this AlertDialog with Pango markup.getBody()Gets the body text ofself.booleanGets whether the body text of this AlertDialog includes Pango markup.Gets the ID of the close response ofself.@Nullable StringGets the ID of the default response ofself.@Nullable WidgetGets the child widget ofself.@Nullable StringGets the heading ofself.booleanGets whether the heading of this AlertDialog includes Pango markup.static MemoryLayoutThe memory layout of the native struct.booleanGets whether this AlertDialog prefers wide layout.getResponseAppearance(String response) Gets the appearance ofresponse.booleangetResponseEnabled(String response) Gets whetherresponseis enabled.getResponseLabel(String response) Gets the label ofresponse.static @Nullable TypegetType()Get the GType of the AlertDialog classbooleanhasResponse(String response) Gets whether this AlertDialog has a response with the IDresponse.onResponse(@Nullable String detail, AlertDialog.ResponseCallback handler) This signal is emitted when the dialog is closed.voidremoveResponse(String id) Removes a response fromself.protected voidvoidSets the body text ofself.voidsetBodyUseMarkup(boolean useMarkup) Sets whether the body text of this AlertDialog includes Pango markup.voidsetCloseResponse(String response) Sets the ID of the close response ofself.voidsetDefaultResponse(@Nullable String response) Sets the ID of the default response ofself.voidsetExtraChild(@Nullable Widget child) Sets the child widget ofself.voidsetHeading(@Nullable String heading) Sets the heading ofself.voidsetHeadingUseMarkup(boolean useMarkup) Sets whether the heading of this AlertDialog includes Pango markup.voidsetPreferWideLayout(boolean preferWideLayout) Sets whether this AlertDialog prefers wide layout.voidsetResponseAppearance(String response, ResponseAppearance appearance) Sets the appearance forresponse.voidsetResponseEnabled(String response, boolean enabled) Sets whetherresponseis enabled.voidsetResponseLabel(String response, String label) Sets the label ofresponsetolabel.Methods inherited from class org.gnome.adw.Dialog
addBreakpoint, close, closeAttempt, closed, emitCloseAttempt, emitClosed, forceClose, getCanClose, getChild, getContentHeight, getContentWidth, getCurrentBreakpoint, getDefaultWidget, getFocus, getFollowsContentSize, getPresentationMode, getTitle, onCloseAttempt, onClosed, present, setCanClose, setChild, setContentHeight, setContentWidth, setDefaultWidget, setFocus, setFollowsContentSize, setPresentationMode, setTitleMethods inherited from class org.gnome.gtk.Widget
actionSetEnabled, activateActionIfExists, activateDefault, activateWidget, addController, addCssClass, addMnemonicLabel, addTickCallback, allocate, childFocus, computeBounds, computeExpand, computeExpand, computePoint, computeTransform, contains, createPangoContext, createPangoLayout, cssChanged, directionChanged, disposeTemplate, dragCheckThreshold, emitDestroy, emitDirectionChanged, emitHide, emitKeynavFailed, emitMap, emitMnemonicActivate, emitMoveFocus, emitQueryTooltip, emitRealize, emitShow, emitStateFlagsChanged, emitUnmap, emitUnrealize, errorBell, focus, getAllocatedBaseline, getAllocatedHeight, getAllocatedWidth, getAllocation, getAncestor, getBaseline, getCanFocus, getCanTarget, getChildVisible, getClipboard, getColor, getCssClasses, getCssName, getCursor, getDefaultDirection, getDirection, getDisplay, getFirstChild, getFocusable, getFocusChild, getFocusOnClick, getFontMap, getFontOptions, getFrameClock, getHalign, getHasTooltip, getHeight, getHexpand, getHexpandSet, getLastChild, getLayoutManager, getLimitEvents, getMapped, getMarginBottom, getMarginEnd, getMarginStart, getMarginTop, getName, getNative, getNextSibling, getOpacity, getOverflow, getPangoContext, getParent, getPreferredSize, getPrevSibling, getPrimaryClipboard, getRealized, getReceivesDefault, getRequestMode, getRoot, getScaleFactor, getSensitive, getSettings, getSize, getSizeRequest, getStateFlags, getStyleContext, getTemplateChild, getTooltipMarkup, getTooltipText, getValign, getVexpand, getVexpandSet, getVisible, getWidth, grabFocus, hasCssClass, hasDefault, hasFocus, hasVisibleFocus, hide, inDestruction, initTemplate, insertActionGroup, insertAfter, insertBefore, isAncestor, isDrawable, isFocus, isSensitive, isVisible, keynavFailed, listMnemonicLabels, map, measure, mnemonicActivate, moveFocus, observeChildren, observeControllers, onDestroy, onDirectionChanged, onHide, onKeynavFailed, onMap, onMnemonicActivate, onMoveFocus, onQueryTooltip, onRealize, onShow, onStateFlagsChanged, onUnmap, onUnrealize, pick, pick, queryTooltip, queueAllocate, queueDraw, queueResize, realize, removeController, removeCssClass, removeMnemonicLabel, removeTickCallback, root, setCanFocus, setCanTarget, setChildVisible, setCssClasses, setCursor, setCursorFromName, setDefaultDirection, setDirection, setFocusable, setFocusChild, setFocusOnClick, setFontMap, setFontOptions, setHalign, setHasTooltip, setHexpand, setHexpandSet, setLayoutManager, setLimitEvents, setMarginBottom, setMarginEnd, setMarginStart, setMarginTop, setName, setOpacity, setOverflow, setParent, setReceivesDefault, setSensitive, setSizeRequest, setStateFlags, setStateFlags, setTooltipMarkup, setTooltipText, setValign, setVexpand, setVexpandSet, setVisible, shouldLayout, show, sizeAllocate, sizeAllocate, snapshot, snapshotChild, stateFlagsChanged, systemSettingChanged, translateCoordinates, triggerTooltipQuery, unmap, unparent, unrealize, unroot, unsetStateFlags, unsetStateFlagsMethods inherited from class org.gnome.gobject.GObject
addToggleRef, addWeakPointer, bindProperty, bindProperty, bindProperty, bindPropertyFull, bindPropertyFull, bindPropertyWithClosures, bindPropertyWithClosures, compatControl, connect, connect, connect, constructed, disconnect, dispatchPropertiesChanged, dispose, dupData, dupQdata, emit, emitNotify, finalize_, forceFloating, freezeNotify, get, getData, getProperty, getProperty, getProperty, getQdata, getv, interfaceFindProperty, interfaceInstallProperty, interfaceListProperties, isFloating, newInstance, newInstance, newv, notify, notify, notifyByPspec, onNotify, ref, refSink, removeToggleRef, removeWeakPointer, replaceData, replaceQdata, runDispose, set, setData, setDataFull, setProperty, setProperty, setProperty, setQdata, setQdataFull, setv, stealData, stealQdata, takeRef, thawNotify, unref, watchClosure, weakRef, weakUnref, withPropertiesMethods inherited from class org.gnome.gobject.TypeInstance
callParent, callParent, cast, getPrivate, readGClass, writeGClassMethods inherited from class org.javagi.base.ProxyInstance
equals, handle, hashCodeMethods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.gnome.gtk.Accessible
announce, getAccessibleParent, getAccessibleRole, getAtContext, getBounds, getFirstAccessibleChild, getNextAccessibleSibling, getPlatformState, resetProperty, resetRelation, resetState, setAccessibleParent, updateNextAccessibleSibling, updatePlatformState, updateProperty, updateRelation, updateStateMethods inherited from interface org.gnome.gtk.Buildable
getBuildableId
-
Constructor Details
-
AlertDialog
Create a AlertDialog proxy instance for the provided memory address.- Parameters:
address- the memory address of the native object
-
AlertDialog
Creates a newAdwAlertDialog.headingandbodycan be set toNULL. This can be useful if they need to be formatted or use markup. In that case, set them toNULLand callformatBody(java.lang.String, java.lang.Object...)or similar methods afterwards:AdwDialog *dialog; dialog = adw_alert_dialog_new (_("Replace File?"), NULL); adw_alert_dialog_format_body (ADW_ALERT_DIALOG (dialog), _("A file named “%s” already exists. Do you want to replace it?"), filename);- Parameters:
heading- the headingbody- the body text- Since:
- 1.5
-
AlertDialog
public AlertDialog()Creates a new AlertDialog.
-
-
Method Details
-
getType
-
getMemoryLayout
The memory layout of the native struct.- Returns:
- the memory layout
-
asParent
Returns this instance as if it were its parent type. This is mostly synonymous to the Javasuperkeyword, but will set the native typeclass function pointers to the parent type. When overriding a native virtual method in Java, "chaining up" withsuper.methodName()doesn't work, because it invokes the overridden function pointer again. To chain up, callasParent().methodName(). This will call the native function pointer of this virtual method in the typeclass of the parent type. -
addResponse
Adds a response withidandlabeltoself.Responses are represented as buttons in the dialog.
Response ID must be unique. It will be used in
AlertDialog::responseto tell which response had been activated, as well as to inspect and modify the response later.An embedded underline in
labelindicates a mnemonic.setResponseLabel(java.lang.String, java.lang.String)can be used to change the response label after it had been added.setResponseEnabled(java.lang.String, boolean)andsetResponseAppearance(java.lang.String, org.gnome.adw.ResponseAppearance)can be used to customize the responses further.- Parameters:
id- the response IDlabel- the response label- Since:
- 1.5
-
addResponses
Adds multiple responses toself.This is the same as calling
addResponse(java.lang.String, java.lang.String)repeatedly. The variable argument list should beNULL-terminated list of response IDs and labels.Example:
adw_alert_dialog_add_responses (dialog, "cancel", _("_Cancel"), "discard", _("_Discard"), "save", _("_Save"), NULL);- Parameters:
firstId- response idvarargs- label for first response, then more id-label pairs- Since:
- 1.5
-
choose
public void choose(@Nullable Widget parent, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback) This function shows this AlertDialog to the user.If the window is an
WindoworApplicationWindow, the dialog will be shown within it. Otherwise, it will be a separate window.- Parameters:
parent- the parent widgetcancellable- aGCancellableto cancel the operationcallback- a callback to call when the operation is complete- Since:
- 1.5
-
chooseFinish
Finishes thechoose(org.gnome.gtk.Widget, org.gnome.gio.Cancellable, org.gnome.gio.AsyncReadyCallback)call and returns the response ID.- Parameters:
result- aGAsyncResult- Returns:
- the ID of the response that was selected, or
AlertDialog:close-responseif the call was cancelled. - Since:
- 1.5
-
formatBody
-
formatBodyMarkup
Sets the formatted body text of this AlertDialog with Pango markup.The
formatis assumed to contain Pango markup.Special XML characters in the
printf()arguments passed to this function will automatically be escaped as necessary, seeGLib.markupPrintfEscaped(java.lang.String, java.lang.Object...).See
AlertDialog:body.- Parameters:
format- the formatted string for the body text with Pango markupvarargs- the parameters to insert intoformat- Since:
- 1.5
-
formatHeading
-
formatHeadingMarkup
Sets the formatted heading of this AlertDialog with Pango markup.The
formatis assumed to contain Pango markup.Special XML characters in the
printf()arguments passed to this function will automatically be escaped as necessary, seeGLib.markupPrintfEscaped(java.lang.String, java.lang.Object...).See
AlertDialog:heading.- Parameters:
format- the formatted string for the heading with Pango markupvarargs- the parameters to insert intoformat- Since:
- 1.5
-
getBody
-
getBodyUseMarkup
public boolean getBodyUseMarkup()Gets whether the body text of this AlertDialog includes Pango markup.- Returns:
- whether this AlertDialog uses markup for body text
- Since:
- 1.5
-
getCloseResponse
Gets the ID of the close response ofself.- Returns:
- the close response ID
- Since:
- 1.5
-
getDefaultResponse
Gets the ID of the default response ofself.- Returns:
- the default response ID
- Since:
- 1.5
-
getExtraChild
Gets the child widget ofself.- Returns:
- the child widget of
self. - Since:
- 1.5
-
getHeading
Gets the heading ofself.- Returns:
- the heading of
self. - Since:
- 1.5
-
getHeadingUseMarkup
public boolean getHeadingUseMarkup()Gets whether the heading of this AlertDialog includes Pango markup.- Returns:
- whether this AlertDialog uses markup for heading
- Since:
- 1.5
-
getPreferWideLayout
public boolean getPreferWideLayout()Gets whether this AlertDialog prefers wide layout.- Returns:
- whether to prefer wide layout
- Since:
- 1.5
-
getResponseAppearance
Gets the appearance ofresponse.See
setResponseAppearance(java.lang.String, org.gnome.adw.ResponseAppearance).- Parameters:
response- a response ID- Returns:
- the appearance of
response - Since:
- 1.5
-
getResponseEnabled
Gets whetherresponseis enabled.- Parameters:
response- a response ID- Returns:
- whether
responseis enabled - Since:
- 1.5
-
getResponseLabel
Gets the label ofresponse.- Parameters:
response- a response ID- Returns:
- the label of
response - Since:
- 1.5
-
hasResponse
Gets whether this AlertDialog has a response with the IDresponse.- Parameters:
response- response ID- Returns:
- whether this AlertDialog has a response with the ID
response. - Since:
- 1.5
-
removeResponse
Removes a response fromself.- Parameters:
id- the response ID- Since:
- 1.5
-
setBody
Sets the body text ofself.- Parameters:
body- the body of this AlertDialog- Since:
- 1.5
-
setBodyUseMarkup
public void setBodyUseMarkup(boolean useMarkup) Sets whether the body text of this AlertDialog includes Pango markup.- Parameters:
useMarkup- whether to use markup for body text- Since:
- 1.5
-
setCloseResponse
Sets the ID of the close response ofself.It will be passed to
AlertDialog::responseif the dialog is closed by pressingEscapeor with a system action.It doesn't have to correspond to any of the responses in the dialog.
The default close response is
close.- Parameters:
response- the close response ID- Since:
- 1.5
-
setDefaultResponse
Sets the ID of the default response ofself.The button corresponding to this response will be set as the default widget of
self.If not set, the default widget will not be set, and the last added response will be focused by default.
See
Dialog:default-widget.- Parameters:
response- the default response ID- Since:
- 1.5
-
setExtraChild
Sets the child widget ofself.The child widget is displayed below the heading and body.
- Parameters:
child- the child widget- Since:
- 1.5
-
setHeading
Sets the heading ofself.- Parameters:
heading- the heading of this AlertDialog- Since:
- 1.5
-
setHeadingUseMarkup
public void setHeadingUseMarkup(boolean useMarkup) Sets whether the heading of this AlertDialog includes Pango markup.- Parameters:
useMarkup- whether to use markup for heading- Since:
- 1.5
-
setPreferWideLayout
public void setPreferWideLayout(boolean preferWideLayout) Sets whether this AlertDialog prefers wide layout.Prefer horizontal button layout when possible, and wider dialog width otherwise.
- Parameters:
preferWideLayout- whether to prefer wide layout- Since:
- 1.6
-
setResponseAppearance
Sets the appearance forresponse.
Use
ADW_RESPONSE_SUGGESTEDto mark important responses such as the affirmative action, like the Save button in the example.Use
ADW_RESPONSE_DESTRUCTIVEto draw attention to the potentially damaging consequences of usingresponse.This appearance acts as a warning to the user. The Discard button in the example is using this appearance.The default appearance is
ADW_RESPONSE_DEFAULT.Negative responses like Cancel or Close should use the default appearance.
- Parameters:
response- a response IDappearance- appearance forresponse- Since:
- 1.5
-
setResponseEnabled
Sets whetherresponseis enabled.If
responseis not enabled, the corresponding button will haveGtk.Widget:sensitiveset toFALSEand it can't be activated as a default response.responsecan still be used asAlertDialog:close-responsewhile it's not enabled.Responses are enabled by default.
- Parameters:
response- a response IDenabled- whether to enableresponse- Since:
- 1.5
-
setResponseLabel
-
response
-
onResponse
public SignalConnection<AlertDialog.ResponseCallback> onResponse(@Nullable String detail, AlertDialog.ResponseCallback handler) This signal is emitted when the dialog is closed.responsewill be set to the response ID of the button that had been activated.if the dialog was closed by pressing
Escapeor with a system action,responsewill be set to the value ofAlertDialog:close-response.- Parameters:
detail- the signal detailhandler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- Since:
- 1.5
- See Also:
-
emitResponse
Emits the "response" signal. SeeonResponse(java.lang.String, org.gnome.adw.AlertDialog.ResponseCallback). -
builder
AAlertDialog.Builderobject constructs aAlertDialogwith the specified properties. Use the variousset...()methods to set properties, and finish construction withAlertDialog.Builder.build().- Returns:
- the builder object
-