Scarnet
Scarnet

Reputation: 738

Changing SearchView Search Icon Xamarin.Android

I'm trying to change the search icon in a SearchBarRenderer Android custom renderer

and that's what I tried

 Control.Iconified = false;
 Control.SetIconifiedByDefault(false);

 var searchView = Control.FindViewById<ImageView>(Resource.Id.search_button);
 var searchicon = Resources.GetDrawable(Resource.Drawable.search);
 searchView.SetImageDrawable(searchicon);

However, searchIcon is always null

When I looped through the children of SearchView I found and image view with ID 16909229 but setting the image drawable of that didn't change the search icon

Upvotes: 2

Views: 987

Answers (2)

York Shen
York Shen

Reputation: 9084

I'm trying to change the search icon in a SearchBarRenderer Android custom renderer

Modify your code like this:

[assembly:ExportRenderer(typeof(SearchBar), typeof(MySearchBarRenderer))]
namespace yourprjectnamespace
{
    public class MySearchBarRenderer : SearchBarRenderer
    {
        public MySearchBarRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.SearchBar> e)
        {
            base.OnElementChanged(e);

            if (Control != null)
            {
                var searchView = Control;

                int searchViewCloseButtonId = Control.Resources.GetIdentifier("android:id/search_mag_icon", null, null);

                var closeIcon = searchView.FindViewById(searchViewCloseButtonId);
                (closeIcon as ImageView).SetImageResource(Resource.Mipmap.icon);
            }
        }
    }
}

Effect.

Upvotes: 3

fmaccaroni
fmaccaroni

Reputation: 3916

If you are using android.support.v7.widget.SearchView you can try to set it like this:

var searchIcon = (ImageView) searchView.FindViewById(Resource.Id.search_mag_icon);
searchIcon.SetImageResource(Resource.Drawable.my_custom_search_icon);

Source: https://stackoverflow.com/a/20362491/6248510 it's not the same question but it is related to it and in the answer it is included a way to set it

Upvotes: 0

Related Questions