Как изменить цвет фона для отображения предупреждений по умолчанию в xamarin. android? - PullRequest
0 голосов
/ 13 марта 2020

Я хочу изменить цвет фона по умолчанию для отображения предупреждений. Я пробовал много вопросов на разных сайтах. Кто-нибудь может мне помочь?

Ответы [ 2 ]

0 голосов
/ 16 марта 2020

Если вы не хотите использовать Rg.Plugins.Popup, в android вы можете добиться этого с AlertDialog и пользовательским стилем. Вы можете вызвать его по DependencyService.

[assembly: Dependency(typeof(DeviceOpenAlertService))]
namespace App2.Droid
{
    class DeviceOpenAlertService : IDeviceOpenAlertService
    {
        public void Open()
        {

            var alert = new AlertDialog
                 .Builder(CrossCurrentActivity.Current.Activity, Resource.Style.MyDialogStyle)
                 .SetTitle("Alert Title")
                 .SetMessage("Do you want to close this application")
                 .SetPositiveButton("Yes", new myButtonClicklistener())
                 .SetNegativeButton("No", new myButtonClicklistener())
                 .Create();

            alert.Show();
        }
    }
}
* 1006. * Добавьте следующий стиль к styles.xml
 <style name="MyDialogStyle" parent="android:Theme.Material.Light.Dialog.NoActionBar">
    <!--Dialog Background Color-->
    <item name="android:colorBackground">#FF0000</item>

  </style>

  <style name="MyButtonsStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
    <!-- text color for the button -->
    <item name="android:textColor">#00ff00</item>
  </style>

Назовите его в PCL.

 DependencyService.Get<IDeviceOpenAlertService>().Open();

Здесь работает GIF.

enter image description here

0 голосов
/ 15 марта 2020

Вы можете добиться этого поведения, используя Rg.Plugins.Popup , чтобы имитировать c оповещение по умолчанию для отображения, это дает вам больше гибкости в том, как вы хотите, чтобы он выглядел.

Сначала прочитайте Getting Started , на Android вам понадобится это в вашем OnCreate:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    Rg.Plugins.Popup.Popup.Init(this, bundle); //Initialize the plugin

    Xamarin.Forms.Forms.Init(this, bundle);
    LoadApplication (new App ());
}

После этого вам нужно создать View, расширяющийся из PopupPage:

Code Behind:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class AlertPage : PopupPage
{
    public AlertPage()
    {
        InitializeComponent();
    }
}

А вот как выглядит Xaml плечо (я попытался максимально приблизить c предупреждение по умолчанию, вы можете настроить его так, чтобы получить желаемый вид) :

<popup:PopupPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:popup="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
             xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
             x:Class="BlankAppTest.Views.AlertPage">

    <popup:PopupPage.Animation>
        <animations:ScaleAnimation 
            PositionIn="Bottom"
            PositionOut="Bottom"
            ScaleIn="1.2"
            ScaleOut="0.8"
            DurationIn="400"
            DurationOut="300"
            EasingIn="SinOut"
            EasingOut="SinIn"
            HasBackgroundAnimation="True" />
    </popup:PopupPage.Animation>

    <StackLayout Margin="30,0,30,0" VerticalOptions="Center" BackgroundColor="#121212">
        <Grid VerticalOptions="Fill">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"></RowDefinition>
                <RowDefinition Height="*"></RowDefinition>
                <RowDefinition Height="50"></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"></ColumnDefinition>
                <ColumnDefinition Width="50"></ColumnDefinition>
                <ColumnDefinition Width="50"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Label Text="Alert Title" TextColor="White" FontAttributes="Bold" Margin="20,20,20,0"></Label>
            <Label Grid.ColumnSpan="3" TextColor="White" Grid.Row="1" VerticalOptions="StartAndExpand" Text="This is a Custom Popup made it Rg.Plugins.Popup to mimic the Default Android Alert" Margin="20,0"></Label>


            <Label Margin="0,0,0,20" Grid.Column="2" FontAttributes="Bold" Grid.Row="2" VerticalOptions="End" Text="Yes" TextColor="White"></Label>
            <Label Margin="0,0,0,20" Grid.Column="1" FontAttributes="Bold" Grid.Row="2" VerticalOptions="End" Text="No" TextColor="White"></Label>
        </Grid>
    </StackLayout>

</popup:PopupPage>

И это будет работать как обычная страница, вы можете добавить распознаватели жестов к меткам, привязать цвета так, чтобы цвет фона был динами c, все зависит от вас.

Предупреждение по умолчанию:

enter image description here

Окончательный результат:

enter image description here

...