当隐藏键盘时,Xamarin表单按下后不会执行任何操作

问题描述 投票:2回答:2

我正在编写一个Xamarin Forms应用程序(.net标准2.0)。目前它仅针对Android开发,但未来可能会针对其他操作系统发布。我试图管理的场景是这样的:

  • 用户使用单个条目进入ContentPage
  • 我通过在自定义渲染器中使用原生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表单条目中的原因是我可以看到键盘弹出窗口,然后当我在Xamarin Forms控件中请求它时立即消失。我不希望键盘显示,因为这个应用程序主要由具有硬件键盘的工业设备的用户使用,但是该条目需要具有焦点,因为用户将希望立即将文本输入其中。

我的问题是用户必须按两次后退按钮才能在此方案中退出ContentPage。一旦离开隐藏的键盘(并且条目失去焦点),然后再次退出页面。我想避免这种情况 - 他们应该能够在隐藏键盘时只需单击一下即可退出页面。有谁知道如何解决这个问题?我已尝试在自定义渲染器中覆盖OnKeyPreIme,因为其他答案已建议,但它似乎没有检测到后退单击。

android xamarin.forms android-softkeyboard back
2个回答
0
投票

当您的条目集中时,您可以使用隐藏键盘方法。它可能解决了你的问题。

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

0
投票

我(终于)解决了这个问题。关键是不要覆盖OnKeyPreIME而是覆盖DispatchKeyEventPreIme。这允许您拦截“后退”按下。所以,在我的CustomRenderer中我添加了这个方法:

 public override bool DispatchKeyEventPreIme(KeyEvent e)
    {
        //if this is back press and the sip is not visible then we need to call the 'OnBack' method at the view model level
        if(!SIPVisibleListener.IsSIPVisible && e.KeyCode == Keycode.Back)
        {
           if(XamarinFormsControl != null && XamarinFormsControl is IOnBackHandler)
            {
                ((IOnBackHandler)XamarinFormsControl).GoBack();
            }
        }

        return base.DispatchKeyEventPreIme(e);
    }

IOnBackHandler是我创建的用于处理后退按键的界面。 SIPVisibleListener是基于这个问题的答案:How do I Detect if Software Keyboard is Visible on Android Device?希望这会帮助某人。

© www.soinside.com 2019 - 2024. All rights reserved.