xamarin.forms - Xamarin 形式的自定义键盘

标签 xamarin.forms xamarin.ios xamarin.android keyboard

我已经阅读了论坛、StackOverflow 和其他地方关于制作自定义键盘的许多帖子,但还没有找到适用于我的 Xamarin 表单跨平台项目的方法。它以编程方式生成。

例如,我构建了在几个地方推荐的这个键盘:

我尝试将其集成到我的 Xamarin 表单应用程序中,但无法执行此操作

https://github.com/Vaikesh/CustomKeyboard/blob/master/CustomKeyboard/Activity1.cs

它作为一个独立的工作正常

我要 Hebrew language keyboard在我的应用程序中像这样

enter image description here

我将不胜感激任何帮助。

谢谢你。

最佳答案

Custom Keyboard in Xamarin forms



您可以创建一个 PageRenderer并使用 native .axml布局文件以创建自定义 Keyboard .

例如,我的 KeyboardPageRenderer :
[assembly: ExportRenderer(typeof(MyKeyboardPage), typeof(KeyboardPageRenderer))]
...
public class KeyboardPageRenderer : PageRenderer
{

    public CustomKeyboardView mKeyboardView;
    public EditText mTargetView;
    public Android.InputMethodServices.Keyboard mKeyboard;
    Activity activity;
    global::Android.Views.View view;

    protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement != null || Element == null)
        {
            return;
        }

        try
        {
            SetupUserInterface();
            SetupEventHandlers();
            this.AddView(view);
        }
        catch (System.Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(@"           ERROR: ", ex.Message);
        }
    }

    void SetupUserInterface()
    {
        activity = this.Context as Activity;
        view = activity.LayoutInflater.Inflate(Resource.Layout.activity_keyboard, this, false);

        mKeyboard = new Android.InputMethodServices.Keyboard(Context, Resource.Xml.keyboard);
        mTargetView = view.FindViewById<EditText>(Resource.Id.target);

        mKeyboardView = view.FindViewById<CustomKeyboardView>(Resource.Id.keyboard_view);
        mKeyboardView.Keyboard = mKeyboard;
    }

    void SetupEventHandlers()
    {
        mTargetView.Touch += (sender, e) =>
        {
            ShowKeyboardWithAnimation();
            e.Handled = false;
            mTargetView.ShowSoftInputOnFocus = false;
        };

        mKeyboardView.Key += async (sender, e) =>
        {
            long eventTime = JavaSystem.CurrentTimeMillis();
            KeyEvent ev = new KeyEvent(eventTime, eventTime, KeyEventActions.Down, e.PrimaryCode, 0, 0, 0, 0, KeyEventFlags.SoftKeyboard | KeyEventFlags.KeepTouchMode);

            DispatchKeyEvent(ev);

            await Task.Delay(1);

            mTargetView.RequestFocus();
        };
    }


    public void ShowKeyboardWithAnimation()
    {
        if (mKeyboardView.Visibility == ViewStates.Gone)
        {
            mKeyboardView.Visibility = ViewStates.Visible;
            Android.Views.Animations.Animation animation = AnimationUtils.LoadAnimation(
                Context,
                Resource.Animation.slide_in_bottom
            );
            mKeyboardView.ShowWithAnimation(animation);
        }
    }

    protected override void OnLayout(bool changed, int l, int t, int r, int b)
    {
        base.OnLayout(changed, l, t, r, b);

        var msw = MeasureSpec.MakeMeasureSpec(r - l, MeasureSpecMode.Exactly);
        var msh = MeasureSpec.MakeMeasureSpec(b - t, MeasureSpecMode.Exactly);

        view.Measure(msw, msh);
        view.Layout(0, 0, r - l, b - t);
    }
}

效果:

Sample implementation[Effect] .

我写了一个关于如何实现这个功能的简单演示,你可以在这个 GitHub Repository 中看到它。 .

我不懂希伯来语,如果你要达到你发的图片的效果,你需要在keyboard.xml中自定义布局。文件。

更新:

I am done iOS portion using entry render so only try to do for android portion



我写了EntryRenderer要实现此功能,效果类似于 this ,希望可以帮到你。
public class MyEntry2Renderer :  ViewRenderer<MyEntry, TextInputLayout>,
    ITextWatcher,
    TextView.IOnEditorActionListener
{
    private bool _hasFocus;

    public CustomKeyboardView mKeyboardView;
    public Android.InputMethodServices.Keyboard mKeyboard;

    ViewGroup activityRootView;

    protected EditText EditText => Control.EditText;

    public bool OnEditorAction(TextView v, ImeAction actionId, KeyEvent e)
    {
        if ((actionId == ImeAction.Done) || ((actionId == ImeAction.ImeNull) && (e.KeyCode == Keycode.Enter)))
        {
            Control.ClearFocus();
            //HideKeyboard();
            ((IEntryController)Element).SendCompleted();
        }
        return true;
    }

    public virtual void AfterTextChanged(IEditable s)
    {
    }

    public virtual void BeforeTextChanged(ICharSequence s, int start, int count, int after)
    {
    }

    public virtual void OnTextChanged(ICharSequence s, int start, int before, int count)
    {
        if (string.IsNullOrWhiteSpace(Element.Text) && (s.Length() == 0)) return;
        ((IElementController)Element).SetValueFromRenderer(Entry.TextProperty, s.ToString());
    }

    protected override TextInputLayout CreateNativeControl()
    {
        var textInputLayout = new TextInputLayout(Context);
        var editText = new EditText(Context);

        #region Add the custom Keyboard in your Page
        var activity = Forms.Context as Activity;
        var rootView = activity.Window.DecorView.FindViewById(Android.Resource.Id.Content);

        activity.Window.SetSoftInputMode(SoftInput.StateAlwaysHidden);

        activityRootView = ((ViewGroup)rootView).GetChildAt(0) as ViewGroup;
        mKeyboardView = new CustomKeyboardView(Forms.Context, null);

        Android.Widget.RelativeLayout.LayoutParams layoutParams =
            new Android.Widget.RelativeLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.WrapContent); // or wrap_content
        layoutParams.AddRule(LayoutRules.AlignParentBottom);
        activityRootView.AddView(mKeyboardView, layoutParams);
        #endregion

        //First open the current page, hide the Keyboard
        mKeyboardView.Visibility = ViewStates.Gone;

        //Use the custom Keyboard
        mKeyboard = new Android.InputMethodServices.Keyboard(Context, Resource.Xml.keyboard2);
        mKeyboardView.Keyboard = mKeyboard;

        mKeyboardView.Key += async (sender, e) =>
        {
            long eventTime = JavaSystem.CurrentTimeMillis();
            KeyEvent ev = new KeyEvent(eventTime, eventTime, KeyEventActions.Down, e.PrimaryCode, 0, 0, 0, 0, KeyEventFlags.SoftKeyboard | KeyEventFlags.KeepTouchMode);

            DispatchKeyEvent(ev);

            await Task.Delay(1);
        };

        textInputLayout.AddView(editText);
        return textInputLayout;
    }


    protected override void OnElementChanged(ElementChangedEventArgs<MyEntry> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement != null)
            if (Control != null)
                EditText.FocusChange -= ControlOnFocusChange;

        if (e.NewElement != null)
        {
            var ctrl = CreateNativeControl();
            SetNativeControl(ctrl);

            EditText.ShowSoftInputOnFocus = false;

            EditText.FocusChange += ControlOnFocusChange;
        }
    }

    private void ControlOnFocusChange(object sender, FocusChangeEventArgs args)
    {
        _hasFocus = args.HasFocus;
        if (_hasFocus)
        {
            EditText.Post(() =>
            {
                EditText.RequestFocus();
                ShowKeyboardWithAnimation();
            });
        }
        else
        {
            //Hide the Keyboard
            mKeyboardView.Visibility = ViewStates.Gone;
        }
    }

    public void ShowKeyboardWithAnimation()
    {
        if (mKeyboardView.Visibility == ViewStates.Gone)
        {
            mKeyboardView.Visibility = ViewStates.Visible;
            Android.Views.Animations.Animation animation = AnimationUtils.LoadAnimation(
                Context,
                Resource.Animation.slide_in_bottom
            );
            mKeyboardView.ShowWithAnimation(animation);
        }
    }
}

关于xamarin.forms - Xamarin 形式的自定义键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47787385/

相关文章:

c# - 在 MonoTouch 中将 PerformSelector 与 @selector 结合使用

c# - 在我的应用程序中禁用系统字体大小效果

ios - Xamarin Forms iOS11 大标题文本额外空白

c# - Xamarin.Forms:自定义 ListView 单元格的数据绑定(bind)

ios - 如何使用 MonoTouch AudioConverter 将 LinearPCM 转换为压缩格式?

android - xamarin.android permgen 空间错误

android - 清除 SingleChoice ListView 选择

xamarin.android - "You need to use a Theme.AppCompat theme (or descendant) with this activity."Xamarin

c# - 每隔几秒自动刷新或更新内容页面

xamarin - PropertyChanged被触发,但 View 没有更新