Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin.Forms: Android <Entry> and dependency service?

I am learning C# and Xamarin.Forms at the moment, so please treat me like a complete beginner.

I have an entry in my XML in Xamarin.Forms:

<Entry x:Name="temperature" Placeholder="Temperatur" Keyboard="Numeric" Margin="20,0"/>

In my CS:

double temp = double.Parse(temperature.Text);

This all works fine. But I need to use a different kind of entry for Android. Because Xamarin.Forms Entry do not handle decimal separators very well when it comes to Samsung phones.

On Android I want to use NuGet "NumericEditText-Xamarin.Android" like this:

<br.com.akamud.NumericEditText 
android:id="@+id/txtNumeric"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number|numberDecimal" />

It should handle my entry input, and then of course handle the entry after that with the shared code of Xamarin.Forms. Is dependency service the best way to go about solving this?
Would someone be so kind to help me out in the right direction.

like image 303
Bjorn Avatar asked Feb 15 '26 18:02

Bjorn


1 Answers

Dependency service is used to invoke native api on specific project, if the issue is related to UI, a custom renderer is the better choice.

You need to create a custom renderer for a custom view, and replace the view with NumericEditText inside the custom renderer.

Create Custom View

public class EntryView : View
{
}

Usage of Custom view in page

 xmlns:local ="clr-namespace:App2"
 <local:EntryView/>

Custom renderer

[assembly: ExportRenderer(typeof(EntryView), typeof(MyRenderer))]
namespace App2.Droid
{

    public class MyRenderer : Xamarin.Forms.Platform.Android.ViewRenderer<EntryView, NumericEditText>
    {

        Context _context;
        NumericEditText editView;
        public MyRenderer(Context context) : base(context)
        {
            _context = context;
        }


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

            if(e.NewElement != null)
            {
                if (Control == null)
                {
                    editView = new NumericEditText(Context);
                    editView.InputType = InputTypes.NumberFlagDecimal|InputTypes.ClassNumber;
                    SetNativeControl(editView);
                }
            }
        }
    }
}

Refer to https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/view.

like image 109
ColeX - MSFT Avatar answered Feb 18 '26 08:02

ColeX - MSFT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!