Hello @platinum78 ,
Welcome to our Microsoft Q&A platform!
I created a basic demo to test the function, and reproduced the issue on my side. The function code of the custom renderer class works fine if we click the 'Entry' directly to make it focus on. The problem will only occur when calling the Focus()
method. I check the source code about the method but it doesn't provide the working mechanism. We cannot get how the Focus()
method perform in each native platform. If you want to get out this problem, it's suggested to report it to the Xamarin.Forms github repo for help.
To avoid the problem, here is a workaround which uses the native code to set focus for the entry instead. I add a bool
parameter to the custom entry class. Obtain the parameter in the render class to check the value to change the focus status.
Here is the related code, you could refer to:
public class CustomEntry : Entry
{
public static readonly BindableProperty CustomFocusProperty = BindableProperty.Create(nameof(CustomFocus), typeof(bool), typeof(CustomEntry), null);
public bool CustomFocus
{
get => (bool)GetValue(CustomFocusProperty);
set => SetValue(CustomFocusProperty, value);
}
}
[assembly:ExportRenderer(typeof(CustomEntry),typeof(CustomEntryRenderer))]
namespace TestApplication_6.Droid
{
public class CustomEntryRenderer : EntryRenderer
{
public CustomEntryRenderer(Context context) : base(context)
{
}
CustomEntry entry;
EditText editText;
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
entry = Element as CustomEntry;
editText = Control as EditText;
editText.FocusChange += EditText_FocusChange;
}
private void EditText_FocusChange(object sender, FocusChangeEventArgs e)
{
this.Control.ShowSoftInputOnFocus = false;
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (entry.CustomFocus)
{
editText.RequestFocus();
}
else
{
editText.ClearFocus();
}
}
}
}
Change the parameter's value to set focus for the entry:
public partial class TestPage : CustomPage
{
public TestPage()
{
InitializeComponent();
}
private async void Button_Clicked(object sender, EventArgs e)
{
entry.CustomFocus = false;
entry.Text += "testing";
entry.CustomFocus = true;
}
private void Entry_Focused(object sender, FocusEventArgs e)
{
}
}
Best Regards,
Jarvan Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.