Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 204402

Issues with switching focus in Entry.Completed event handler

$
0
0

I have a simple login form with the XAML layout: two entries for username and password and a login button. My application runs on an Android device equipped with a hardware keyboard. The main functionality of the form is to allow the user to key in the username, press Enter key on the hardware keyboard, key in the password, press Enter again, and then finish the login process.

To achieve that, the form must be capable of the following:

  • setting focus to the Username entry upon appearing on the screen;
  • responding to the hardware Enter key by switching focus to the next control.

The first part works fine: the form sets the focus to the UserName entry upon appearing on the screen. However, when I press the hardware Enter key, the focus switches to the button, instead of switching to the next entry. This is the sequence of events occurring on the form:

txtUserName: 'focused' // the form sets the initial focus in OnAppearing()
txtUserName: 'unfocused' // these two lines is the response to the hardware Enter key pressed while focus is in txtUserName
txtUserName: 'completed'
txtPassword: 'focused' // the forms switches the focus to txtPassword following the code in txtUserName_Completed()
txtPassword: 'unfocused' // txtPassword immediately loses focus; this is an unexpected behavior
btnLogin: 'focused' // focus is now on the button

What am I doing wrong? What is the correct way of manipulating focus in the scenario I described?

This is my form.

XAML layout:

    <?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="TestFocus.LoginPage">

      <StackLayout>
        <Entry x:Name="txtUserName" />

        <Entry x:Name="txtPassword" />

        <Button x:Name="btnLogin" Text="Login" />
      </StackLayout>

    </ContentPage>

... and the code-behind file:

using System;
using Xamarin.Forms;

namespace TestFocus
{
    public partial class LoginPage : ContentPage
    {
        public LoginPage()
        {
            InitializeComponent();

            txtUserName.Completed += txtUserName_Completed;
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();

            txtUserName.Focus();
        }

        private void txtUserName_Completed(object sender, EventArgs e)
        {
            txtPassword.Focus();
        }
    }
}

Viewing all articles
Browse latest Browse all 204402

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>