首页 > 解决方案 > 在 Xamarin Android 的 MVVMCross 中从视图模型中关闭键盘

问题描述

我在屏幕上有一个文本视图和一个按钮。用户点击显示键盘的文本视图,用户键入一些文本,然后单击其 onclick 绑定到视图模型中定义的命令的按钮。

我想通过发送消息或调用视图中的方法来从视图模型中解除键盘,但仍希望保持视图和视图模型之间的松散耦合。我看到 mvvmmessenger、mvxinteraction 等来完成这个。处理这个问题的最佳方法是什么?

标签: xamarinxamarin.android

解决方案


不知道这是否是处理此问题的最佳方法,但希望我这样做的方式可以帮助您。

我在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();
    }

} 

推荐阅读