Bug Creator
Bug Creator

Reputation: 11

How do I set the keyboard as a numeric keypad and can I enter a negative number in Xamarin.Forms?

The demand is to display the default number of the keyboard can enter a negative number like this:

enter image description here

But there is no way to set the default for this way.

If you set this keyboard, you can not enter a negative number, click the minus sign is not responding.

Pure numeric keypad, but can not enter a negative number

enter image description here

Is there any solution?

Upvotes: 0

Views: 3286

Answers (1)

Wilson Vargas
Wilson Vargas

Reputation: 2899

You have to create your own control for NumericEntry like:

public class NumericTextBox : Entry
{
    public NumericTextBox()
    {
        this.Keyboard = Keyboard.Numeric;
    }
}

Then, in your Android project, create Custom Renderer:

[assembly: ExportRenderer(typeof(NumericTextBox), typeof(CustomNumericTextboxRenderer))]

namespace xxx.Droid.Renderers
{
    public class CustomNumericTextboxRenderer : EntryRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);

            var native = Control as EditText;

            native.InputType = Android.Text.InputTypes.ClassNumber | Android.Text.InputTypes.NumberFlagSigned | Android.Text.InputTypes.NumberFlagDecimal;
        }
    }
}

This has been tested and working for Droid devices. It allows to enter negative/positive values with decimal point. It properly forbirs entering wrong decimal value.

Upvotes: 3

Related Questions