Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to edit icon of SearchBar Xamarin Forms on Android?

I need your help !

I work on a mobile development project, cross-platform. I use Visual Studio with Xamarin Forms. I want to make a page with a SearchBar (Xamarin.Forms class), but, my problem is the personalisation of the SearchBar icon, especially on the Platform Android. My search led me to nothing. I would be very grateful if you know of a way to edit icon. (I have a model to follow, so It’s well the icon that I want to change and not the color).

Thank you in advance !

enter image description here

like image 826
R.Extrant Avatar asked Dec 04 '22 00:12

R.Extrant


2 Answers

enter image description here

Introduction to Custom Renderers

You can subclass the stock Xamarin.Forms controls fairly easily for making minor platform-oriented changes to the controls.

In the examples above, I create two SearchBar subclasses, one to allow a custom icon and the other to remove the icon, the Xamarin.Android renders look like:

enter image description here

protected override void OnElementChanged (ElementChangedEventArgs<SearchBar> e)
{
    base.OnElementChanged (e);
    if (Control != null) {
        var searchView = Control;
        searchView.Iconified = true;
        searchView.SetIconifiedByDefault (false);
        // (Resource.Id.search_mag_icon); is wrong / Xammie bug
        int searchIconId = Context.Resources.GetIdentifier ("android:id/search_mag_icon", null, null);
        var icon = searchView.FindViewById (searchIconId);
        (icon as ImageView).SetImageResource (Resource.Drawable.icon);
    }

enter image description here

protected override void OnElementChanged (ElementChangedEventArgs<SearchBar> e)
{
    base.OnElementChanged (e);
    if (Control != null) {
        var searchView = Control;
        searchView.Iconified = true;
        searchView.SetIconifiedByDefault (false);
        // (Resource.Id.search_mag_icon); is wrong / Xammie bug
        int searchIconId = Context.Resources.GetIdentifier ("android:id/search_mag_icon", null, null);
        var icon = searchView.FindViewById (searchIconId);
        icon.Visibility = Android.Views.ViewStates.Gone;

    }
}
like image 101
SushiHangover Avatar answered Jan 17 '23 13:01

SushiHangover


@SushiHangover's method works fine, but icon appears again once SearchView get focus. To fix this, I use LayoutParameters for icon:

if(Control!= null){
    ...
    int searchIconId = Context.Resources.GetIdentifier ("android:id/search_mag_icon", null, null);
    var icon = (ImageView)searchView.FindViewById (searchIconId);
    icon.LayoutParameters = new LinearLayout.LayoutParams (0, 0);
    ...
}
like image 20
Cuckooshka Avatar answered Jan 17 '23 15:01

Cuckooshka