Changing keyboard's ImeOptions of Xamarin.Forms.Entry in custom renderer not working on Android

瘦欲@ 提交于 2019-12-06 07:43:20

I found a workaround for my problem myself:

First I added an Action to my custom entry to be called when I press my "search"-button.

MyEntry.cs

namespace CustomEntry
{
    public class MyEntry:Entry
    {
        public Action SearchPressed = delegate {
        };
    }
}

Second I "listen" for ImeAction.Search like this and call the Action I added to my custom entry.

MyEntryRenderer.cs (Android):

[assembly: ExportRenderer(typeof(MyEntry), typeof(MyEntryRenderer))]
namespace CustomEntry.Android
{
    public class MyEntryRenderer:EntryRenderer
    {

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

            if (Control != null) {
                Control.ImeOptions = ImeAction.Search;
                Control.EditorAction += (sender, args) => {
                    if (args.ActionId == ImeAction.Search) {
                        var entry = (AddressEntry)Element;
                        entry.SearchPressed();
                    }
                };
            }
        }

    }
}

In a third class where I use MyEntry I can run some code when the "search"-button is pressed like this:

var myEntry = new MyEntry();
myEntry.SearchPressed += SomeMethod;

public class EntryExtensionRenderer : EntryRenderer { protected override void OnElementChanged(ElementChangedEventArgs e) { base.OnElementChanged(e);

        if ((Element as EntryExtension).NoSuggestionsKey)
        {
            Control.AutocorrectionType = UITextAutocorrectionType.No;
        }

        if ((Element as EntryExtension).ReturnKeyType.Equals("Done"))
        {
            this.AddDoneButton("Done", (EntryExtension)Element);
        }
        else if ((Element as EntryExtension).ReturnKeyType.Equals("Next"))
        {
            this.AddDoneButton("Next", (EntryExtension)Element);
        }
    }

    protected void AddDoneButton(string button, EntryExtension entry)
    {
        UIToolbar toolbar = new UIToolbar(new RectangleF(0.0f, 0.0f, 50.0f, 44.0f));

        var doneButton = new UIBarButtonItem();

        if (button.Equals("Done")) { 
            doneButton = new UIBarButtonItem(UIBarButtonSystemItem.Done, delegate
            {
                entry.KeyPressedEnter();
            });
        }

        if (button.Equals("Next"))
        {
            doneButton = new UIBarButtonItem("Next", UIBarButtonItemStyle.Done, delegate
            {
                entry.KeyPressedEnter();
            });
        }

        toolbar.Items = new UIBarButtonItem[] {
            new UIBarButtonItem (UIBarButtonSystemItem.FlexibleSpace),
            doneButton
        };
        this.Control.InputAccessoryView = toolbar;
    }


}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!