Xamarin Forms Material Entry force numeric keyboard

Travis Doke 1 Reputation point
2021-05-22T18:57:59.707+00:00

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!

Developer technologies .NET Xamarin
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. JessieZhang-MSFT 7,716 Reputation points Microsoft External Staff
    2021-05-24T06:25:23.87+00:00

    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.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.