问题描述
在Xamarin.forms便携式表单项目中聚焦Entry
时,如何隐藏软键盘以显示?我认为我们必须为此编写平台特定的渲染器,但是以下方法不起作用:
How do I hide the softkeyboard for showing up when focusing an Entry
in Xamarin.forms portable forms project? I assume we have to write platform specific renderers for that, but the following does not work:
我创建自己的条目子类:
I create my own entry subclass:
public class MyExtendedEntry : Entry
{
}
,然后在xamarin.android项目中渲染我的渲染器:
and then in the xamarin.android project my renderer:
public class MyExtendedEntryRenderer : EntryRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (Control != null)
{
new Handler().Post(delegate
{
var imm = (InputMethodManager)Control.Context.GetSystemService(Context.InputMethodService);
var result = imm.HideSoftInputFromWindow(Control.WindowToken, 0);
});
}
}
}
OnElementChanged
被按预期方式调用,当使用Handler.Post()
时,我也获得了WindowToken而不是null.遗憾的是,HideSoftInputFromWindow
的返回值始终为false,并且在单击Entry时,软键盘仍会打开.
The OnElementChanged
is called as expected and when using Handler.Post()
I also get a WindowToken instead of null. Sadly the return value from HideSoftInputFromWindow
is always false and the softkeyboard still turns up when clicking on the Entry.
推荐答案
OnElementChanged
.您要做的是单击该条目时隐藏键盘,因此您应该将FocusChange
的事件处理程序添加到Control
.
OnElementChanged
is called whenever the view is initialized and attached to the view. What you want to do is to hide the keyboard when the entry is clicked, so you should add an event handler to FocusChange
to the Control
.
示例:
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.Click += (sender, evt) => {
new Handler().Post(delegate
{
var imm = (InputMethodManager)Control.Context.GetSystemService(Android.Content.Context.InputMethodService);
var result = imm.HideSoftInputFromWindow(Control.WindowToken, 0);
Console.WriteLine(result);
});
};
Control.FocusChange += (sender, evt) => {
new Handler().Post(delegate
{
var imm = (InputMethodManager)Control.Context.GetSystemService(Android.Content.Context.InputMethodService);
var result = imm.HideSoftInputFromWindow(Control.WindowToken, 0);
Console.WriteLine(result);
});
};
}
}
更新:@Vikram的组合答案
Update: Combined answer from @Vikram
更新:添加了Click
事件处理程序
Update: Added Click
event handler
这篇关于在Xamarin中隐藏软键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!