This is just a simplified example, but I\'m trying to set this up so that when I open up this page in my Application, the first thing that happens is the keyboard pops up re
Use the Focus
method
nameentry.Focus();
If you want the focus to be set when your page appears, you should probably do this in the OnAppearing
method
protected override void OnAppearing ()
{
base.OnAppearing ();
nameentry.Focus();
}
Can anyone explain to me why this doesn't work
protected override void OnAppearing()
{
base.OnAppearing();
CustomerNameEntry.Focus();
}
But this does (adding async and Task.Delay(1))
protected override async void OnAppearing()
{
base.OnAppearing();
await Task.Delay(1);
CustomerNameEntry.Focus();
}
I'd rather not add this clutter, it seems hacky but it's the only way I've been able to get it to work (I've also tried invoking on main thread, to no avail).
So long as the element to focus on is the topmost element, this should work. I place this in the OnAppearing
method.
base.OnAppearing();
Entry entry = this.FindByName<Entry>("NameOfEntryElement");
entry.Focus();
The source of this info is here: https://forums.xamarin.com/discussion/100354/entry-focus-not-working-for-android
There is further discussion in the article about timing issues.
I know this is an old thread but this might work for someone as it worked for me.
protected override async void OnAppearing()
{
base.OnAppearing();
await Task.Delay(500);
await Task.Run(() =>
{
entryname.Focus();
});
}
In one of my projects I did something like this. Please try the following example:
public class EntryFocusBehavior : Behavior<Entry>
{
public string NextFocusElementName { get; set; }
protected override void OnAttachedTo(Entry bindable)
{
base.OnAttachedTo(bindable);
bindable.Completed += Bindable_Completed;
}
protected override void OnDetachingFrom(Entry bindable)
{
bindable.Completed -= Bindable_Completed;
base.OnDetachingFrom(bindable);
}
private void Bindable_Completed(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(NextFocusElementName))
return;
var parent = ((Entry)sender).Parent;
while (parent != null)
{
var nextFocusElement = parent.FindByName<Entry>(NextFocusElementName);
if (nextFocusElement != null)
{
nextFocusElement.Focus();
break;
}
else
{
parent = parent.Parent;
}
}
}
}
And then XAML:
!!! Please let me know if I made a mistake in the code.
Just inside OnAppearing(), add the following code,
protected async override void OnAppearing()
{
await Task.Run(() =>
{
Task.Delay(100);
Device.BeginInvokeOnMainThread(async () =>
{
txtName.Focus();
});
});
}
Note: txtName is the reference name of your Entry Field.