Mounika
Mounika

Reputation: 147

How to detect backspace in an Entry control when it is empty

I am using Xamarin.Forms with Android. I have a form which has 4 Entry controls for a user to enter code. I am using TextChanged event to detect user input and automatically move focus to the next control. This part works fine, i.e. as user types a digit focus automatically jumps to the next entry. However, I need to achieve the opposite, user should be able to tap backspace button and focus should move to the previous control. The problem is that TextChanged is not triggered when entry control is empty. How can I achieve this? Is there a custom renderer I can create for android to capture text input? Maybe there is a way to use 1 entry instead but I need to make it look like distinct 4 boxes.

Upvotes: 2

Views: 1645

Answers (1)

Mounika
Mounika

Reputation: 147

Finally,I've found a solution for this by implementing a renderer in android.

In shared code(PCL),Create a class like this

public class CustomEntry:Entry
{
    public delegate void BackspaceEventHandler(object sender, EventArgs e);

    public event BackspaceEventHandler OnBackspace;

    public CustomEntry()
    {

    }

    public void OnBackspacePressed()
    {
        if (OnBackspace != null)
        {
            OnBackspace(null, null);
        }
    }
}

And,Then in your android project create a renderer like this:

 public class CustomEntryRenderer: EntryRenderer
 {
    public override bool DispatchKeyEvent(KeyEvent e)
    {
        if (e.Action == KeyEventActions.Down)
        {
            if (e.KeyCode == Keycode.Del)
            {
                if (string.IsNullOrWhiteSpace(Control.Text))
                {
                    var entry = (PasswordBox)Element;
                    entry.OnBackspacePressed();
                }
            }
        }
        return base.DispatchKeyEvent(e);
    }

    protected override void 
    OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Entry> e)
    {
        base.OnElementChanged(e);
    }
}

And then use it like this:

Entry1.OnBackspace += Entry1BackspaceEventHandler;

public void Entry1BackspaceEventHandler()
{
//things you want to do
}

Upvotes: 3

Related Questions