From 1ca347fac65c68bb5a32830d456b74bc9a28e7ab Mon Sep 17 00:00:00 2001 From: amelazzi Date: Thu, 26 Aug 2021 18:36:35 +0200 Subject: [PATCH] :bug: cant set dot on decimal input --- .../CustomEntryRenderer.cs | 51 +++++++++++++++---- .../Inputs/Views/FormEntry.xaml | 1 + 2 files changed, 42 insertions(+), 10 deletions(-) diff --git a/Smartway.UiComponent.Sample.Android/CustomEntryRenderer.cs b/Smartway.UiComponent.Sample.Android/CustomEntryRenderer.cs index 286b97c..a5a2bc7 100644 --- a/Smartway.UiComponent.Sample.Android/CustomEntryRenderer.cs +++ b/Smartway.UiComponent.Sample.Android/CustomEntryRenderer.cs @@ -1,6 +1,11 @@ -using Android.Content; +using System.Globalization; +using System.Linq; +using System.Text.RegularExpressions; +using Android.Content; using Android.Graphics.Drawables; using Android.Runtime; +using Android.Text; +using Android.Text.Method; using Android.Widget; using Smartway.UiComponent.Sample.Droid; using Xamarin.Forms; @@ -19,19 +24,45 @@ protected override void OnElementChanged(ElementChangedEventArgs e) { base.OnElementChanged(e); - if (Control != null) - { - GradientDrawable gd = new GradientDrawable(); - gd.SetColor(global::Android.Graphics.Color.Transparent); + if (Control == null) + return; - this.Control.SetPadding(0, 0, Control.PaddingRight, 0); + var gd = new GradientDrawable(); + gd.SetColor(global::Android.Graphics.Color.Transparent); - if (e.OldElement != null) - return; + Control.SetPadding(0, 0, Control.PaddingRight, 0); - RemoveHintBottomLine(); - SetCursorColor(); + if (Control.InputType.HasFlag(InputTypes.NumberFlagDecimal)) + { + Control.KeyListener = DigitsKeyListener.GetInstance("0123456789.,"); + Control.TextChanged += Control_TextChanged; } + + if (e.OldElement != null) + return; + + RemoveHintBottomLine(); + SetCursorColor(); + } + + private const string DecimalRegEx = @"^\d+((\.|\,){1})?\d*$"; + private void Control_TextChanged(object sender, Android.Text.TextChangedEventArgs e) + { + var control = sender as FormsEditText; + control.SetSelection(control.Text.Length); + + var lastChar = e.Text?.LastOrDefault(); + if (lastChar != ',' && lastChar != '.') + return; + + if (!Regex.IsMatch(control.Text, DecimalRegEx)) + control.Text = control.Text.Remove(control.Text.Length - 1); + + var cultureDecimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; + if (lastChar.ToString() == cultureDecimalSeparator) + return; + + control.Text = control.Text.Replace(lastChar.ToString(), cultureDecimalSeparator); } private void SetCursorColor() diff --git a/Smartway.UiComponent.Sample/Inputs/Views/FormEntry.xaml b/Smartway.UiComponent.Sample/Inputs/Views/FormEntry.xaml index 44b41cb..df3ab8b 100644 --- a/Smartway.UiComponent.Sample/Inputs/Views/FormEntry.xaml +++ b/Smartway.UiComponent.Sample/Inputs/Views/FormEntry.xaml @@ -13,6 +13,7 @@ +