xamarin - 在 Xamarin Android 的 MVVMCross 中从视图模型中关闭键盘
问题描述
我在屏幕上有一个文本视图和一个按钮。用户点击显示键盘的文本视图,用户键入一些文本,然后单击其 onclick 绑定到视图模型中定义的命令的按钮。
我想通过发送消息或调用视图中的方法来从视图模型中解除键盘,但仍希望保持视图和视图模型之间的松散耦合。我看到 mvvmmessenger、mvxinteraction 等来完成这个。处理这个问题的最佳方法是什么?
解决方案
不知道这是否是处理此问题的最佳方法,但希望我这样做的方式可以帮助您。
我在Core项目中做了一个叫IPlatformAction的接口,它实现了一个叫DismissKeyboard的方法。
public interface IPlatformAction
{
void DismissKeyboard();
}
然后我在 Droid 项目中创建了一个名为 PlatformActionService 的服务,它实现了该接口。
public class PlatformService : IPlatformAction
{
protected Activity CurrentActivity =>
Mvx.IoCProvider.Resolve<IMvxAndroidCurrentTopActivity>().Activity;
public void DismissKeyboard()
{
var currentFocus = CurrentActivity.CurrentFocus;
if (currentFocus != null)
{
InputMethodManager inputMethodManager = (InputMethodManager)CurrentActivity.GetSystemService(Context.InputMethodService);
inputMethodManager.HideSoftInputFromWindow(currentFocus.WindowToken, HideSoftInputFlags.None);
}
}
}
最后,我在视图模型中注入接口并调用解除键盘方法
public class SomeViewModel : BaseViewModel<SomeModel>
{
private readonly IPlatformAction _platformAction;
public SomeViewModel(IPlatformAction platformAction)
{
_platformAction = platformAction;
}
public async Task DoSomething()
{
//Some code
_platformAction.DismissKeyboard();
}
}
推荐阅读
- html - EXCEL:如果填充了一组列,则使用返回值的函数
- java - Android 应用程序中的空对象引用
- vba - 为什么图表对象粘贴方法不起作用?
- python - 如何在 Python 中将提取的文本从 PDF 转换为 JSON 或 XML 格式?
- android - 点击 RecylerView 项目下载多个文件并显示下载进度
- mysql - Excel VBA QueryTable 参数因空值而失败
- android - 生成的 APK 文件没有“src”代码
- openmp - 低效的openMP并行单nowait
- c++ - 我的 QuadTree 实现遇到问题
- materialize - 如何在具体化 v1 日期选择器上的日期范围之间进行选择