red_panda
red_panda

Reputation: 35

MAUI Searchbar icon not firing event

When i click search icon near text entry it doesnt trigger event, but when i do click enter on keyoboard it does work.

<SearchBar
    x:Name="SearchBar"
    Grid.Column="1"
    CancelButtonColor="White"
    FontSize="18"
    SearchButtonPressed="SearchBar_SearchButtonPressed"
    SearchCommand="{Binding SearchCommand}"
    SearchCommandParameter="{Binding Text, Source={x:Reference SearchBar}}"
    Text="{Binding SearchText}"
    VerticalOptions="Center" />
       public async void SearchBar_SearchButtonPressed(object sender, EventArgs e)
       {
           await DisplayAlert("hi", SearchBar.Text, "ok");
       }

Command is getting triggered as well on enter key

public ICommand SearchCommand => new Command<string>(async (text) =>
{
    await Application.Current.MainPage.DisplayAlert("hi", $"{text} - {this.SearchText}", "ok");
});

whats wrong with it?

Upvotes: 3

Views: 127

Answers (1)

Liqun Shen-MSFT
Liqun Shen-MSFT

Reputation: 8260

There is no default event when clicking the Searchbar icon in Maui Android. But you may set an extra one through Handler. Here is an example,

In MainPage, I implement a ModifySearchbarOnlyforAndroid method in which I use Handler. I use FindViewById to find the search bar icon first and then set a Click event on it,

        public MainPage()
        {
            InitializeComponent();
            //this.BindingContext = new MainPageViewModel();

            ModifySearchbarOnlyforAndroid();

        }


        void ModifySearchbarOnlyforAndroid()
        {
            Microsoft.Maui.Handlers.SearchBarHandler.Mapper.AppendToMapping("MyCustomization", (handler, view) =>
            {
#if ANDROID
                var searchicon = handler.PlatformView.FindViewById(Resource.Id.search_mag_icon);
                searchicon.SetOnClickListener(new CustomClickListener());
#endif
            });
        }

This is CustomClickListener,

#if ANDROID
    public class CustomClickListener : Java.Lang.Object, IOnClickListener
    {
 
        public void OnClick(Android.Views.View? v)
        {
            //Console.WriteLine("123");
            // add your code here,
        }

    }
#endif

So, the difference is, instead of adding your logic in SearchBar_SearchButtonPressed event handler, now you may add your code in OnClick method in your CustomClickListener.

Upvotes: 0

Related Questions