priya_d
priya_d

Reputation: 403

How to move search icon of search bar at right hand side in xamarin forms

How to move search icon of search bar at right hand side in xamarin forms. I am looking for android and IOS. For Android I used SearchBarRenderer With below code which does not worked Anyone know how to do it?Please help.

 protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
    {
        base.OnElementChanged(e);
        Control.LayoutParameters=(new ActionBar.LayoutParams(GravityFlags.Right));
    }

Upvotes: 3

Views: 2003

Answers (1)

Sparsha Bhattarai
Sparsha Bhattarai

Reputation: 703

In android, with a custom renderer, you can use the following code to place the search icon at the right side of your search bar:

    protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
    {
        base.OnElementChanged(e);
        if (e.NewElement != null)
        {
            var searchView = base.Control as SearchView;

            //Get the Id for your search icon
            int searchIconId = Context.Resources.GetIdentifier("android:id/search_mag_icon", null, null);
            ImageView searchViewIcon = (ImageView)searchView.FindViewById<ImageView>(searchIconId);
            ViewGroup linearLayoutSearchView = (ViewGroup)searchViewIcon.Parent;

            searchViewIcon.SetAdjustViewBounds(true);

            //Remove the search icon from the view group and add it once again to place it at the end of the view group elements
            linearLayoutSearchView.RemoveView(searchViewIcon);
            linearLayoutSearchView.AddView(searchViewIcon);
        }
    }

In the above implementation, I simply removed the search icon from the search bar view group and then added it again to the same view group. This placed the normally first child to the last child, thus placing the search icon at the end.

Upvotes: 1

Related Questions