如何更改选择器下划线的颜色?

时间:2019-09-05 17:27:44

标签: forms xamarin picker

我用Xamarin Forms编写应用程序。我已使用自定义渲染器将“输入”下划线颜色设置为透明。我还需要以相同的方式将选择器的底线颜色设置为透明,但是它不起作用。我从此处完成了一个示例:https://alexdunn.org/2017/07/24/xamarin-tip-borderless-picker/并将Control.BackgroundColor设置为透明,但没有效果。在Xamarin.Android styles.xml中,要更改的是重音颜色,但是在点击时仅更改底线的颜色,并且对所有应用程序都有影响(不好)。下划线的规则黑色保持不变。还有其他解决方案,还是最好放弃Xamarin Forms的选择器并创建自己的自定义弹出窗口?

1 个答案:

答案 0 :(得分:0)

您可以使用 CustomRenderer

在iOS中

using System;
using App1.iOS;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(Picker), typeof(MyiOSPicker))]
namespace App1.iOS
{
    public class MyiOSPicker : PickerRenderer, IUIPickerViewDelegate, IUIPickerViewDataSource
    {

        string SelectedValue;

        public MyiOSPicker()
        {

        }

        public nint GetComponentCount(UIPickerView pickerView)
        {
            return 1;
        }

        public nint GetRowsInComponent(UIPickerView pickerView, nint component)
        {
            return Element.Items.Count;
        }

        [Export("pickerView:viewForRow:forComponent:reusingView:")]
        public UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view)
        {


            foreach(UIView line in pickerView.Subviews)
            {
                if(line.Frame.Height<1)
                {
                    line.BackgroundColor = UIColor.Red;   // set line coloer here!!!!
                }
            }

            UILabel label = new UILabel
            {
                //here you can set the style of item!!!

                TextColor = UIColor.Blue,

                Text = Element.Items[(int)row].ToString(),

                TextAlignment = UITextAlignment.Center,

            };
            return label;
        }


        [Export("pickerView:didSelectRow:inComponent:")]
        public void Selected(UIPickerView pickerView, nint row, nint component)
        {
            Control.Text = Element.Items[(int)row];
            SelectedValue = Element.Items[(int)row];
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
        {
            base.OnElementChanged(e);

            if (Control != null)
            {
                SelectedValue = Element.Items[0];

                UIPickerView pickerView = (UIPickerView)Control.InputView;
                pickerView.WeakDelegate = this;
                pickerView.DataSource = this;


                UIToolbar toolbar = (UIToolbar)Control.InputAccessoryView;

                UIBarButtonItem done = new UIBarButtonItem("Done", UIBarButtonItemStyle.Done, (object sender, EventArgs click) =>
                {
                    Control.Text = SelectedValue;
                    toolbar.RemoveFromSuperview();
                    pickerView.RemoveFromSuperview();
                    Control.ResignFirstResponder();
                });
                toolbar.Items = new UIBarButtonItem[] { done };
            }

        }
    }
}

enter image description here

在Android中

using System;
using System.Linq;
using Java.Lang.Reflect;
using Android.App;
using Android.Content;
using Android.Views;
using Android.Widget;
using App1.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Android.Graphics.Drawables;

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

        private AlertDialog _dialog;

        public MyAndroidPicker(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement == null || e.OldElement != null)
                return;

            Control.Click += Control_Click;
        }

        protected override void Dispose(bool disposing)
        {
            Control.Click -= Control_Click;
            base.Dispose(disposing);
        }


        private void SetPickerDividerColor(TextColorNumberPicker picker)
        {
            Field[] fields = picker.Class.GetDeclaredFields();

            foreach (Field pf in fields)
            {


                if (pf.Name.Equals("mSelectionDivider"))
                {
                    pf.Accessible = true;
                    // set the line color here!!!
                    pf.Set(picker, new ColorDrawable(Android.Graphics.Color.Yellow));

                }
            }

        }


        private void Control_Click(object sender, EventArgs e)
        {

            Picker model = Element;

            var picker = new TextColorNumberPicker(Context);
            if (model.Items != null && model.Items.Any())
            {

                picker.MaxValue = model.Items.Count - 1;
                picker.MinValue = 0;
              //  picker.SetBackgroundColor(Android.Graphics.Color.Yellow);
                picker.SetDisplayedValues(model.Items.ToArray());

                //call the method after you setting DisplayedValues

                picker.WrapSelectorWheel = false;
                picker.Value = model.SelectedIndex;

                SetPickerDividerColor(picker);
            }

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

            ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, true);

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

            builder.SetTitle(model.Title ?? "");
            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();
        }

    }

    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 ) {

            //set the font of text
            ((EditText)view).TextSize = 12;
        }
      }
    }
}

enter image description here

您还可以根据需要设置其他样式。