我正在编写 Xamarin Forms 应用程序(.net 标准 2.0)。目前它仅针对 Android 开发,但将来可能会针对其他操作系统发布。我试图管理的场景是这样的:
- 用户通过一个 Entry 进入 ContentPage
我通过在自定义渲染器中使用 native Android 代码来赋予 Entry 焦点:
if (e.NewElement != null && e.NewElement is CustomEntry) { CustomEntry customEntry = (CustomEntry)e.NewElement; if(customEntry.GiveFocus) { //this messes up the onback behaviour - you have to press onback twice to exit the screen, once to get out of the hidden SIP Control.RequestFocus(); } }
我不想让软键盘自动弹出。因此,我在 MainActivity 的 OnCreate 中添加了以下行:
Window.SetSoftInputMode(SoftInput.StateAlwaysHidden);
我请求焦点在自定义渲染器中而不是在 Xamarin Forms Entry 中的原因是我可以看到键盘弹出窗口,然后当我在 Xamarin Forms 控件中请求它时立即消失。我不希望键盘出现,因为此应用主要供使用硬件键盘的工业设备用户使用,但条目需要有焦点,因为用户希望立即在其中输入文本。
我的问题是在这种情况下用户必须按两次后退按钮才能退出 ContentPage。一次退出隐藏键盘(并且 Entry 失去焦点)然后再次退出页面。我想避免这种情况——当键盘被隐藏时,他们应该只需单击一下就可以退出页面。有谁知道如何解决这个问题?正如其他答案所建议的那样,我尝试在自定义渲染器中覆盖 OnKeyPreIme,但它似乎没有检测到后退点击。
最佳答案
当您的条目获得焦点时,您可以使用隐藏键盘方法。它可能会解决你的问题。
public interface IKeyboardHelper
{
void HideKeyboard();
}
对于 Android 使用:
public class DroidKeyboardHelper : IKeyboardHelper
{
public void HideKeyboard()
{
var context = Forms.Context;
var inputMethodManager = context.GetSystemService(Context.InputMethodService) as InputMethodManager;
if (inputMethodManager != null && context is Activity)
{
var activity = context as Activity;
var token = activity.CurrentFocus?.WindowToken;
inputMethodManager.HideSoftInputFromWindow(token, HideSoftInputFlags.None);
activity.Window.DecorView.ClearFocus();
}
}
}
对于 iOS:
public class iOSKeyboardHelper : IKeyboardHelper
{
public void HideKeyboard()
{
UIApplication.SharedApplication.KeyWindow.EndEditing(true);
}
}
使用 Dependency Injection
并在您的条目获得焦点时调用此方法。
尝试使用下面的方法来处理后退按钮按下事件。
protected override bool OnBackButtonPressed()
{
// you can handle back button pressed event in Xamarin forms page
return base.OnBackButtonPressed();
}
关于android - 隐藏键盘时,Xamarin Forms 按回键不执行任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51513794/