Пользовательское средство выбора Xamarin Android

У меня есть пикер. Подскажите, пожалуйста, как изменить цвет заголовка, цвет элементов и убрать эти строки

введите здесь описание изображения

У меня есть свой выборщик, и я могу изменить цвет кнопок ОТМЕНА, ОК. Я попытался удалить строки https://forums.xamarin.com/discussion/78693/how-can-i-remove-the-picker-границы-в-формах-для-Android но не работает Как изменить цвет SELECT A CAR и AUDI не знаю

введите здесь описание изображения

[2]: https://i.stack.imgur.com/tbKsC.png


person Maria Kamenskyh    schedule 21.08.2020    source источник


Ответы (1)


Вы можете реализовать это с помощью Custom Renderer.

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

using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using App12.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Color = Android.Graphics.Color;
using Orientation = Android.Widget.Orientation;

[assembly: ExportRenderer(typeof(Picker), typeof(MyPickerRenderer))]
namespace App12.Droid
{
    public class MyPickerRenderer:PickerRenderer
    {
        IElementController ElementController => Element;


        public MyPickerRenderer(Context context) : base(context)
        {
         

        }


        private AlertDialog _dialog;


        protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
        {
            base.OnElementChanged(e);
            Control.Click += Control_Click;

            Control.SetHintTextColor(Android.Graphics.Color.Red);
            Control.SetSingleLine(true);
            Control.SetTypeface(null, TypefaceStyle.Bold);
            Control.Gravity = GravityFlags.Center;

            var gd = new GradientDrawable();
            gd.SetStroke(0, Android.Graphics.Color.Transparent);
            Control.SetBackground(gd);

        }


        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                Control.Click -= Control_Click;
                //var picker = (Picker)Element;
                //picker.PropertyChanged -= Control_Click;
            }


            base.Dispose(disposing);
        }

        private void Control_Click(object sender, EventArgs e)
        {
            Picker model = Element;
           
            picker.SelectionDividerHeight = 0;

            var picker = new TextColorNumberPicker(Context);

            if (model.Items != null && model.Items.Any())
            {
                // set style here

                picker.MaxValue = model.Items.Count - 1;
                picker.MinValue = 0;

              
                picker.SetDisplayedValues(model.Items.ToArray());
                picker.WrapSelectorWheel = false;
                picker.Value = model.SelectedIndex;

            }


            var layout = new LinearLayout(Context) { Orientation = Orientation.Vertical };
            layout.AddView(picker);

            var titleView = new TextView(Context);

            titleView.Text = "Select a car";
            titleView.TextSize = 20;
            titleView.SetTextColor(Color.Red);
            titleView.SetBackgroundColor(Color.White);

            ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, true);

            var builder = new AlertDialog.Builder(Context);
            builder.SetView(layout);

            builder.SetTitle(model.Title ?? "");

            builder.SetCustomTitle(titleView);
            builder.SetNegativeButton("Cancel  ", (s, a) =>
            {
                ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
                // It is possible for the Content of the Page to be changed when Focus is changed.
                // In this case, we'll lose our Control.
                Control?.ClearFocus();
                _dialog = null;
            });
            builder.SetPositiveButton("Ok ", (s, a) =>
            {
                ElementController.SetValueFromRenderer(Picker.SelectedIndexProperty, picker.Value);
                // It is possible for the Content of the Page to be changed on SelectedIndexChanged.
                // In this case, the Element & Control will no longer exist.
                if (Element != null)
                {
                    if (model.Items.Count > 0 && Element.SelectedIndex >= 0)
                        Control.Text = model.Items[Element.SelectedIndex];
                    ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
                    // It is also possible for the Content of the Page to be changed when Focus is changed.
                    // In this case, we'll lose our Control.
                    Control?.ClearFocus();
                }
                _dialog = null;
            });


            _dialog = builder.Create();
            _dialog.DismissEvent += (ssender, args) =>
            {
                ElementController?.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
            };
            _dialog.Show();

            Android.Widget.Button btnOk = _dialog.GetButton((int)Android.Content.DialogButtonType.Positive);
            btnOk.SetTextColor(Android.Graphics.Color.Blue);

            Android.Widget.Button btnCancel = _dialog.GetButton((int)Android.Content.DialogButtonType.Positive);
            btnCancel.SetTextColor(Android.Graphics.Color.Gray);
        }



        
    }


    public class TextColorNumberPicker : NumberPicker
    {
        public TextColorNumberPicker(Context context) : base(context)
        {

        }

        public override void AddView(Android.Views.View child, int index, ViewGroup.LayoutParams @params)
        {
            base.AddView(child, index, @params);
            UpdateView(child);
        }

        public void UpdateView(Android.Views.View view)
        {
            if (view is EditText)
            {


                ((EditText)view).SetTextColor(Color.Red);  // set item text color 


            }
        }
    }

}

Примечание. Убедитесь, что целевая платформа проекта является последней стабильной версией (Android Q).

введите здесь описание изображения

person Lucas Zhang    schedule 21.08.2020
comment
Я не понимаю. У меня ошибка. Пишет, что функция не оввериде. Но вы написали оввериде, я редактирую и показываю ошибку - person Maria Kamenskyh; 21.08.2020
comment
Это работает. Вы можете помочь мне еще раз? Можете ли вы сказать, что я должен добавить в пользовательское средство выбора, чтобы добавить изображение? Я добавляю изображение выше - person Maria Kamenskyh; 21.08.2020