Reputation: 1962
I am trying to remove the black underline under the SearchBar Control on Android. I wrote a CustomRender that I thought would accomplish this, but no luck:
[assembly: ExportRenderer(typeof(NoUnderlineSearchBar), typeof(NoUnderlineSearchBarRenderer))]
namespace XamarinDemo.Droid.CustomRenderers
{
public class NoUnderlineSearchBarRenderer : SearchBarRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
{
base.OnElementChanged(e);
if (Control != null)
{
this.Control.SetBackgroundColor(Android.Graphics.Color.Argb(0, 0, 0, 0));
}
}
}
}
This seems to work for Entry fields, but not SearchBars. Does anyone know how I can remove the SearchBar underline in a Custom Renderer? Thanks!
Upvotes: 7
Views: 5165
Reputation: 16652
You're right about creating a custom renderer, but in your renderer, to remove the underline, we need to find the plate of SearchView
in native android first. You can for example code like this:
protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
{
base.OnElementChanged(e);
if (Control != null)
{
var plateId = Resources.GetIdentifier("android:id/search_plate", null, null);
var plate = Control.FindViewById(plateId);
plate.SetBackgroundColor(Android.Graphics.Color.Transparent);
}
}
Upvotes: 19
Reputation: 1237
This is to extend the answer above by @Grace.
In other examples I have came across following snippet:
protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
{
base.OnElementChanged(e);
if (Control != null)
{
LinearLayout linearLayout = this.Control.GetChildAt(0) as LinearLayout;
linearLayout = linearLayout.GetChildAt(2) as LinearLayout;
linearLayout = linearLayout.GetChildAt(1) as LinearLayout;
linearLayout.Background = null; //removes underline
}
}
However, on Android Lolipop and below linearLayout.Background = null;
will result in
Attempt to invoke virtual method 'boolean android.graphics.drawable.Drawable.setState(int[])' on a null object reference xamarin search bar
Hence I would replace the code above on my answer with answer from Grace's as follows:
if (Control != null)
{
var plateId = Resources.GetIdentifier("android:id/search_plate", null, null);
var plate = Control.FindViewById(plateId);
plate.SetBackgroundColor(Android.Graphics.Color.Transparent);
}
Upvotes: 1