Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin.Forms Entry change cursor color

I try to change the cursor color on a Xamarin Forms Entry. So far I followed the solution by this Forum Post:

https://forums.xamarin.com/discussion/138361/change-cursor-color-in-entry

Which is this code in a custom renderer:

IntPtr IntPtrtextViewClass = JNIEnv.FindClass(typeof(TextView));
IntPtr mCursorDrawableResProperty = JNIEnv.GetFieldID(IntPtrtextViewClass, "mCursorDrawableRes", "I");

// my_cursor is the xml file name which we defined above
JNIEnv.SetField(Control.Handle, mCursorDrawableResProperty, Resource.Drawable.my_cursor);

Unfortunately this doesn't work anymore on my Android Q Emulator / Device. I get this exception:

Java.Lang.NoSuchFieldError: no "I" field "mCursorDrawableRes" in class "Landroid/widget/TextView;"

Is there another way to do it?

Sample: https://1drv.ms/u/s!Ang3D30bKDOhqPATE80z8n3pUX9JxQ?e=L08oiB

like image 536
NPadrutt Avatar asked Oct 19 '25 03:10

NPadrutt


2 Answers

If someone facing a crash while compiling the project with android SDK 10 (Q) then please do this way:

    if (Build.VERSION.SdkInt >= BuildVersionCodes.Q)
    {
        Control.SetTextCursorDrawable(0); //This API Intrduced in android 10
    }
    else
    {
        IntPtr IntPtrtextViewClass = JNIEnv.FindClass(typeof(TextView));
        IntPtr mCursorDrawableResProperty = JNIEnv.GetFieldID(IntPtrtextViewClass, "mCursorDrawableRes", "I");
        JNIEnv.SetField(Control.Handle, mCursorDrawableResProperty, 0);
    }

Cheers!

like image 75
Mohammad Riyaz Avatar answered Oct 22 '25 04:10

Mohammad Riyaz


When you use EntryRenderer, the Control is type of Entry:

protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{

    base.OnElementChanged(e);
    Control.SetTextCursorDrawable(Resource.Drawable.my_cursor);

}

While when you use MaterialEntryRenderer, the Control is type of MaterialFormsTextInputLayout, so it won't work when you change the mCursorDrawableRes of MaterialFormsTextInputLayout, it even can't be found so you get the exception, the correct way is :

public class EntryRendererForAndroid : MaterialEntryRenderer
{
    public EntryRendererForAndroid(Context context) : base(context)
    {

    }

    protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
    {

        base.OnElementChanged(e);

        Control.EditText.SetTextCursorDrawable(Resource.Drawable.my_cursor);

    }
}
like image 26
nevermore Avatar answered Oct 22 '25 04:10

nevermore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!