我将如何设置 Xamarin Forms Android Picker 弹出窗口的背景颜色

Posted

技术标签:

【中文标题】我将如何设置 Xamarin Forms Android Picker 弹出窗口的背景颜色【英文标题】:How would I set the background colour of a Xamarin Forms Android Picker popup 【发布时间】:2021-11-12 13:26:22 【问题描述】:

我正在尝试为单击 xamarin 表单中的选择器时出现的弹出窗口设置背景颜色。但是,更改的背景颜色是针对您单击以显示弹出窗口的对象,而不是弹出窗口本身,如下所示

我尝试使用自定义渲染器和 Control.BackgroundTintList 来解决此问题,该渲染器在类似情况下也有效,但这似乎无济于事。我尝试的另一件事是在 DatePicker 中尽可能使用 styles.xml,但我也没有运气,因为 Picker 显然没有对话框。

谷歌搜索提供了很多关于如何使用自定义渲染器仅针对 ios 执行此操作的教程,但我找不到任何用于实际更改背景颜色的 android

非常欢迎任何建议。

【问题讨论】:

【参考方案1】:

您始终可以使用 ListView 创建另一个视图,当一个项目被选中时,它会关闭并返回结果。这样您就可以在每个平台上使用它并修改背景颜色、选项颜色和所有内容。

如果你这样做,你可以在另一个页面中进行,只需使用 PushModalAsync,或者使用 AbsoluteLayout 或 GridLayout 来显示其他元素

【讨论】:

【参考方案2】:

您可以创建一个自定义选择器弹出窗口,然后您将能够以更多方式对其进行样式设置,并且它应该适用于 iOS 和 Android。以下是您可以做什么的简单示例:

XAML

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="listInPopUp.MainPage">

    <AbsoluteLayout Padding="0" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
        <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
            <Button Text="Display Prompt!"
                VerticalOptions="CenterAndExpand"
                HorizontalOptions="Center"
                Clicked="OnButtonClicked" />
        </StackLayout>


        <ContentView x:Name="popupView" BackgroundColor="#C0808080" Padding="10, 0" IsVisible="false" AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="All">
            <StackLayout VerticalOptions="Center" HorizontalOptions="Center">
                <StackLayout Orientation="Vertical" HeightRequest="220" WidthRequest="200" BackgroundColor="Aqua">
                    <ContentView Padding="12, 0, 0, 0" HorizontalOptions="StartAndExpand">
                        <Label FontSize="16" FontAttributes="Bold" TextColor="Black" Text="Title" />
                    </ContentView>
                    <ListView x:Name="OptionList" ItemSelected="OnItemClicked" ItemsSource="Binding MyList" SeparatorVisibility="None" VerticalScrollBarVisibility="Never">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <ViewCell>
                                    <Label Text="Binding ." />
                                </ViewCell>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
                    <Button Text="Cancel" HorizontalOptions="End" TextColor="Black" FontSize="16"  BackgroundColor="Aqua" TextTransform="None" Clicked="Cancel_Clicked" />
                </StackLayout>
            </StackLayout>
        </ContentView>
    </AbsoluteLayout>

</ContentPage>

C#

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace listInPopUp

    public partial class MainPage : ContentPage
    
        public ObservableCollection<string> MyList  get; set;  = new ObservableCollection<string>();
        public MainPage()
        
            InitializeComponent();
            MyList.Add("Option 1");
            MyList.Add("Option 2");
            MyList.Add("Option 3");
            BindingContext = this;
        

        void OnButtonClicked(object sender, EventArgs args)
        
            //This will show the pop up
            popupView.IsVisible = true;
        

        private void OnItemClicked(object sender, SelectedItemChangedEventArgs e)
        
            popupView.IsVisible = false;
            var item = e.SelectedItem as String;
            if (item != null)
            
                if (item == "Option 1")
                
                    //Do something
                
                // etc.
            
        
        private void Cancel_Clicked(object sender, EventArgs e)
        
            popupView.IsVisible = false;
            //Your stuff here
        
    

这会给你一个像这样的弹出窗口(@98​​7654325@ 和 StackLayoutButton 你可以改变弹出窗口的背景。你也可以设置其他的样式):

【讨论】:

【参考方案3】:

您可以使用自定义渲染器来定义自定义对话框。

自定义渲染器:

  [assembly: ExportRenderer(typeof(Picker), typeof(AndroidPickerRenderer))]
  namespace App10.Droid

public class AndroidPickerRenderer : PickerRenderer

    private Context context;
    AlertDialog listDialog;
    string[] items;

    public AndroidPickerRenderer(Context context) : base(context)
    
        this.context = context;
    
    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Picker> e)
    
        base.OnElementChanged(e);


        if (Control != null)
        
            Control.Click += Control_Click;
        
    

    private void Control_Click(object sender, EventArgs e)
    
        Picker model = Element;
        items = model.Items.ToArray();
        AlertDialog.Builder builder =
       new AlertDialog.Builder(context);
        builder.SetTitle(model.Title ?? "");
        builder.SetNegativeButton("Cancel", (s, a) =>
        
            Control?.ClearFocus();
            builder = null;
        );
        Android.Views.View view = LayoutInflater.From(context).Inflate(Resource.Layout.listview, null);
        Android.Widget.ListView listView = view.FindViewById<Android.Widget.ListView>(Resource.Id.listView1);

        MyAdapter myAdapter = new MyAdapter(items, Element.SelectedIndex);
        listView.Adapter = myAdapter;
        listView.ItemClick += ListView_ItemClick;
        builder.SetView(view);
        listDialog = builder.Create();
        listDialog.Window.DecorView.SetBackgroundColor(Android.Graphics.Color.Pink); // set the dialog background color 
        listDialog.Show();
        Android.Widget.Button button = listDialog.GetButton((int)DialogButtonType.Negative);
        button.Text = "Cancel";
        button.Click += Button_Click;
        button.SetTextColor(Android.Graphics.Color.Blue); // set the button bottom color
    

    private void Button_Click(object sender, EventArgs e)
    
        listDialog.Dismiss();
        listDialog = null;
    

    private void ListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
    
        Control.Text = items[e.Position];
        Element.SelectedIndex = e.Position;
        listDialog.Dismiss();
        listDialog = null;
    

    class MyAdapter : BaseAdapter
    
        private string[] items;
        private int selectedIndex;

        public MyAdapter(string[] items)
        
            this.items = items;
        

        public MyAdapter(string[] items, int selectedIndex) : this(items)
        
            this.selectedIndex = selectedIndex;
        

        public override int Count => items.Length;

        public override Java.Lang.Object GetItem(int position)
        
            return items[position];
        

        public override long GetItemId(int position)
        
            return position;
        

        public override Android.Views.View GetView(int position, Android.Views.View convertView, ViewGroup parent)
        
            if (convertView == null)
            
                convertView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.listview_item, null);
            
            TextView textView = convertView.FindViewById<TextView>(Resource.Id.textView1);
            textView.Text = items[position];
            return convertView;
        
    
 

Xaml:

    <Picker x:Name="picker"  Title="Title" VerticalOptions="CenterAndExpand" >
        <Picker.ItemsSource>
            <x:Array Type="x:Type x:String">
                <x:String>Option 1</x:String>
                <x:String>Option 2</x:String>
                <x:String>Option 3</x:String>
            </x:Array>
        </Picker.ItemsSource>
    </Picker>

listview.xml:您可以在 android 项目中创建 Resources/layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_
    android:layout_>
    <ListView
       android:id="@+id/listView1"
       android:layout_
       android:layout_/>


</LinearLayout>

listview_item.xml :您可以在您的Resources/layout android 项目中创建。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_
    android:layout_>
   <TextView
      android:id="@+id/textView1"
      android:layout_
      android:layout_/>
</LinearLayout>

截图:

【讨论】:

以上是关于我将如何设置 Xamarin Forms Android Picker 弹出窗口的背景颜色的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Xamarin Forms 中处理/取消导航

Xamarin.Forms Android 保留汉堡包/菜单图标而不是后退按钮

如何在 Xamarin Forms 中以适当的图像比例在 UWP 中设置 SpashScreen?

如何调试 Xamarin.Forms XAML

Xamarin.Forms(2.5.0.122203)使用Zxing.Net.Mobile.Forms(2.3.3)时,Android端莫名崩溃

如何在 XAML [Xamarin.Forms] 中使用 String 以外的类型设置自定义属性值