question

TravisDoke-4824 avatar image
0 Votes"
TravisDoke-4824 asked JessieZhang-2116 commented

Xamarin Forms Material Entry force numeric keyboard

Does anyone know how to force a numeric only keyboard to show for a material design entry using xamarin forms visual material. I have tried setting keyboard to numeric like a normal entry and it doesn't work. I have also tried setting the input type in the android renderer and that doesn't work. Help!

dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

JessieZhang-2116 avatar image
0 Votes"
JessieZhang-2116 answered JessieZhang-2116 commented

Hello,


Welcome to our Microsoft Q&A platform!

To restrict the Entry to only accept numbers you could use a Behavior or a Trigger.

Both of those will react to a user typing into them. So for your use, you could have the trigger or behavior look for any characters that are not numbers and remove them.

You can refer to the following code:

 public class NumericValidationBehavior : Behavior<Entry> {

     protected override void OnAttachedTo(Entry entry) {
         entry.TextChanged += OnEntryTextChanged;
         base.OnAttachedTo(entry);
     }

     protected override void OnDetachingFrom(Entry entry) {
         entry.TextChanged -= OnEntryTextChanged;
         base.OnDetachingFrom(entry);
     }

     private static void OnEntryTextChanged(object sender, TextChangedEventArgs args) 
     {

         if(!string.IsNullOrWhiteSpace(args.NewTextValue)) 
         { 
              bool isValid = args.NewTextValue.ToCharArray().All(x=>char.IsDigit(x)); //Make sure all characters are numbers

             ((Entry)sender).Text = isValid ? args.NewTextValue : args.NewTextValue.Remove(args.NewTextValue.Length - 1);
         }
     }
 }

Uasge:

   <Entry x:Name="AgeEntry"
          VerticalOptions="FillAndExpand"
          HorizontalOptions="FillAndExpand"
          Keyboard="Numeric">
     <Entry.Behaviors>
       <local:NumericValidationBehavior />
     </Entry.Behaviors>
   </Entry>

Refer: https://stackoverflow.com/questions/44475667/is-it-possible-specify-xamarin-forms-entry-numeric-keyboard-without-comma-or-dec/44476195

Best Regards,


Jessie Zhang


If the response is helpful, please click "Accept Answer" and upvote it.



Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.



· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

So it was a mistake by me. I had a base view that all my entries derived from. On that base view I set IsUppercase to true which must cause the numeric keyboard to be ignored on Android.

0 Votes 0 ·

Do you mean you have found the solution, right? Congrats.

0 Votes 0 ·