how to change background colors of a Display Alert

Bruno Silva 26 Reputation points
2022-08-31T12:43:01.15+00:00

How can I change the screen background and button of a DisplayAlert popup, to get good colors on dark and normal screen

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,294 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 26,316 Reputation points Microsoft Vendor
    2022-09-02T09:22:35.633+00:00

    Hello @Bruno Silva ,

    Please define the styles for the dialog under dark and light themes. You can open styles.xaml in the Resources/values folder in your Android project, then define the styles.

    <style name="MyDialogLightStyle" parent="android:Theme.Material.Dialog.NoActionBar">  
    <!--Dialog Background Color-->  
    <item name="android:colorBackground">#FF0000</item>  
    </style>  
    <style name="MyDialogDarkStyle" parent="android:Theme.Material.Dialog.NoActionBar">  
    <!--Dialog Background Color-->  
    <item name="android:colorBackground">#FFF</item>  
    </style>  
    

    Then you can use DependencyService to call the native Android code. And you can try to obtain theme information by Xamarin.Essentials: App Theme, then set different style for the AlertDialog.

        public class DeviceOpenAlertService : IAlertService  
        {  
        public void DisplayAlert()  
        {  
        Xamarin.Essentials.AppTheme theme = AppInfo.RequestedTheme;// get the theme  
        AlertDialog alert;  
    switch (theme){  
        case Xamarin.Essentials.AppTheme.Dark:// for dark theme  
         alert = new AlertDialog  
    .Builder(MainActivity.Instance, Resource.Style.MyDialogDarkStyle)  
    .SetTitle("Alert Title")  
    .SetMessage("Do you want to close this application")  
    .SetPositiveButton("Yes", (c, ev) =>{// Ok button click task})  
    .SetNegativeButton("No", (c, ev) =>{...})  
    .Create();  
        break;  
    ...//for light theme  
        }  
    }  
    

    After that , you can call it in forms : DependencyService.Get<IAlertService>().DisplayAlert();

    Best Regards,
    Wenyan Zhang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments