colorAccent not working inside of a SearchBar

Tupý Šimon 21 Reputation points
2022-09-29T08:58:06.92+00:00

I'm trying to change the color of the cursor inside of a SearchBar element, but I'm having trouble doing so. So far I've tried using colorAccent, but it doesn't seem to work inside of a search bar (it works for entries).

note that I'm only trying to find a solution for android.

Developer technologies | .NET | Xamarin
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2022-09-30T07:27:12.837+00:00

    Hello,

    You can do the following steps to change cursor color in android.

    Firstly: Define your own cursor drawable, then you can create a drawable folder in the Resources folder, you need to create a xml file called cursor_primary.xml and put following code in it. Note: If you cannnot find the @color/colorRed, please add <color name="colorRed">#ff0000</color> in your colors.xml file.

       <?xml version="1.0" encoding="utf-8"?>  
       <shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle">     
           <solid android:color="@color/colorRed"/>  
           <size android:width="2dp"/>  
       </shape>  
    

    Second, you need to to use custom renderer to custom SearchBar like following code.

       [assembly: ExportRenderer(typeof(SearchBar), typeof(MySearchBarRender))]  
         
         
         
       namespace App1.Droid  
       {  
           internal class MySearchBarRender : SearchBarRenderer  
           {  
               public MySearchBarRender(Context context) : base(context)  
               {  
               }  
               protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)  
               {  
                   base.OnElementChanged(e);  
                   if (Control!=null)  
                   {  
                       Android.Widget.SearchView searchView = Control as Android.Widget.SearchView;  
                       Android.Widget.EditText edittext = searchView.FindViewById(Resource.Id.search_src_text) as Android.Widget.EditText;  
                       edittext.SetTextCursorDrawable(Resource.Drawable.cursor_primary);  
                   }  
                    
               }  
           }  
       }  
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.