Xamarin.Forms изменить цвет кнопок и цвет границы в alertDialog - PullRequest
0 голосов
/ 21 февраля 2020

У меня есть AlertDialog. По умолчанию параметр alertDialog выглядит следующим образом:

enter image description here

Я хочу изменить цвет кнопки ОК и добавить цвет границы. Есть ли решение для этой настройки. Это мой код:

   await Application.Current.MainPage.DisplayAlert("Alert!", " This is DisplayAlert", "OK");

Ответы [ 3 ]

1 голос
/ 23 февраля 2020

Вы можете использовать кросс-платформенные библиотеки, подобные этой: https://github.com/aritchie/userdialogs

0 голосов
/ 24 февраля 2020

Вы можете использовать [DependencyService] для вызова нативного AlerDialog и изменить его на определенных c платформах. Вот простой пример изменения цвета кнопки действия.

в Формах , создайте интерфейс:

public interface IPopUp
{
    void Popup(string title, string message,Color titleColor,Color messageColor,Color OKButtonColor ,EventHandler handler);
}

в iOS

using System;
using System.Collections.Generic;
using System.Linq;



using System.Text;
using App10.iOS;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using App10;



[assembly: Dependency(typeof(PopupImplemention))]
namespace App10.iOS
{
    public class PopupImplemention : IPopUp
    {
        public void Popup(string title, string message, Color titleColor, Color messageColor, Color OKButtonColor, EventHandler handler)
        {
            UIAlertController alertController = UIAlertController.Create(title,message,UIAlertControllerStyle.Alert);




            var firstAttributes = new UIStringAttributes
            {
                ForegroundColor =titleColor.ToUIColor(),

            };



            var secondAttributes = new UIStringAttributes
            {
                ForegroundColor =messageColor.ToUIColor(),

            };



            alertController.SetValueForKey(new NSAttributedString(title, firstAttributes), new NSString("attributedTitle"));
            alertController.SetValueForKey(new NSAttributedString(message, secondAttributes), new NSString("attributedMessage"));



            UIAlertAction cancelAction = UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,null);
            UIAlertAction okAction = UIAlertAction.Create("OK", UIAlertActionStyle.Default,(sender)=> { handler?.Invoke(sender, new EventArgs()) ; });





            okAction.SetValueForKey(OKButtonColor.ToUIColor(), new NSString("_titleTextColor"));



            alertController.AddAction(cancelAction);
            alertController.AddAction(okAction);



            var currentViewController = topViewControllerWithRootViewController(UIApplication.SharedApplication.Delegate.GetWindow().RootViewController);
            currentViewController.PresentViewController(alertController,true,null);
        }





        UIViewController topViewControllerWithRootViewController(UIViewController rootViewController)
        {
            if (rootViewController is UITabBarController)
            {
                UITabBarController tabBarController = (UITabBarController)rootViewController;
                return topViewControllerWithRootViewController(tabBarController.SelectedViewController);
            }
            else if (rootViewController is UINavigationController)
            {
                UINavigationController navigationController = (UINavigationController)rootViewController;
                return topViewControllerWithRootViewController(navigationController.VisibleViewController);
            }
            else if (rootViewController.PresentedViewController != null)
            {
                UIViewController presentedViewController = rootViewController.PresentedViewController;
                return topViewControllerWithRootViewController(presentedViewController);
            }
            else
            {
                return rootViewController;
            }
        }
    }
}

в Android

в MainActivity

public static MainActivity Intance;

protected override void OnCreate(Bundle savedInstanceState)
{
  TabLayoutResource = Resource.Layout.Tabbar;
  ToolbarResource = Resource.Layout.Toolbar;

  base.OnCreate(savedInstanceState);
  Intance = this;

  Xamarin.Essentials.Platform.Init(this, savedInstanceState);
  global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

  LoadApplication(new App());
}
using Xamarin.Forms;

using xxx;
using xxx.Droid;
using Android;
using System;
using Xamarin.Forms.Platform.Android;
using Android.Support.V7.App;
using Android.Text;

[assembly: Dependency(typeof(PopupImplemention))]
namespace xxx.Droid
{
    public class PopupImplemention : IPopUp
    {
        public void Popup(string title, string message, Color titleColor, Color messageColor, EventHandler handler)
        {

            // because html.string could not support format string , so you need to set the color directly in the string with a static value

            Android.Support.V7.App.AlertDialog.Builder alert = new Android.Support.V7.App.AlertDialog.Builder(MainActivity.Intance);
            alert.SetTitle(title);
            alert.SetMessage(message);

            alert.SetPositiveButton(Html.FromHtml("<font color='#0000ff'>OK</font>"), (senderAlert, args) =>
            {
                handler?.Invoke(senderAlert, args);
            });
                Android.Support.V7.App.AlertDialog dialog = alert.Create();
            dialog.Show();


        }
    }
}

И назовите это в формах

 DependencyService.Get<IPopUp>().Popup("Title","xxxxxxxxxxxx",Color.Red,Color.Blue,Color.Green,(sen,args)=> { 

       // handle the logic when  clikc the OK button   

});
0 голосов
/ 21 февраля 2020

Вам нужно будет создать стили. xml и таким образом настроить его для Android. Насколько мне известно, в настоящее время нет способа настроить этот собственный элемент управления с помощью API-интерфейса Xamarin.Forms.

Пример:

 <style name="AppCompatAlertDialogStyle" parent="Theme.AppCompat.Dialog.Alert">
    <item name="colorAccent">#c7ac56</item>
    <item name="android:textColor">#c7ac56</item>
    <item name="android:background">#5c8487</item>
  </style>

Вот хороший учебник на примере о том, как это сделать: http://gmariotti.blogspot.com/2015/04/a-material-styled-alertdialog.html

Если вы используете Xamarin Android, вы, вероятно, могли бы также подключиться к AlertDialog.Builder и установить соответствующие параметры программно: https://developer.android.com/reference/android/app/AlertDialog.Builder

...