Xamarin forms – Clear entry control effect

When using the Entry control of Xamarin forms, we don’t have a standard fast way to let the user clear his typed in text.

It would be nice if we could add a Clear icon on the right side of the entry control that clears the current text when tapped.
Example Android and iOS:

Android previewiOS preview

Let me show you how this can be done with an Effect for Xamarin forms!

Do read up on how to create effects in Xamarin forms here…

First iOS, because this is actually the easiest to implement.
In your iOS project add a folder called Effects and in it add a new class file called ClearEntryEffect.cs.
The code for this file is as follows

In this effect, we just get hold of the UITextField native control of the Entry and adjust the ClearButtonMode property to UITextFieldViewMode.WhileEditing. This is possible due to the fact that the iOS UITextField actually has this feature build in, we only need to trigger it.
So one down, one more to go…

Android is a bit trickier, because the native EditText control does not have this pre build in, in other words we need to add this ourselves.
Again add an Effects folder, but now in the Android project and again add a ClearEntryEffect.cs class file.
The code for this one looks like

The code is not all that different, we just need to add some extra tweaking…
First, we add a Clear icon on the right side of the EditText control, this can be done with the editText.SetCompoundDrawablesRelativeWithIntrinsicBounds method on the EditText control.
You add a correct resource id to the correct position, we want it to the right hand side, so it needs to be the third parameter.
Secondly we are going to add a touch listener to the EditText control, using the SetOnTouchListener method.
In this touch listener, we verify if the EditText control is being tapped, MotionEventActions.Up, if so we verify what the actual position was where the user has tapped. If this location is anywhere inside the region of the right drawable, we clear the text of the EditText control.
You get the actual position from the touch event through the event arguments, e.RawX and we calculate the position of the drawable and compare these two values: e.RawX >= (editText.Right – editText.GetCompoundDrawables()[2].Bounds.Width())

So that wasn’t that hard, only needed to read up a bit on Android because I’m still a novice on this one.

After adding these 2 effects, only thing left to do is use them in your Xamarin forms pages!
Thing to remember here is that you still have to create a dummy class in the PCL as well… so add a class file called ClearEntryEffect.cs inside the PCL with following code

And when this is all done, you can use it in your xaml as follows

As always everything can be found on my GitHub here…

Leave a Reply

Your email address will not be published. Required fields are marked *