Java.Lang.NoSuchMethodError: 'no non-static method "Landroid/widget/TextView;.setJustificationMode(I)V"'

Viewed 911

I used the Custom render to sort the text but it does not work on some devices and throws this error:

Java.Lang.NoSuchMethodError: 'no non-static method "Landroid/widget/TextView;.setJustificationMode(I)V"'

Thanks if anyone helps.

This is my code:



[assembly: ExportRenderer(typeof(CustomLabel), typeof(CustomLabelRender))]


namespace customlabel.Droid


{


    public class CustomLabelRender : LabelRenderer


    {
        public CustomLabelRender(Context context) : base(context)
        {

        }


        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            if (Control != null)
            {
                Control.JustificationMode = JustificationMode.InterWord;
            }
        }


    }


}
2 Answers

The error is because this method was first introduced on Android on API Version 26 so that means that on devices with older versions of Android it will crash.

More info here: https://developer.android.com/reference/android/widget/TextView#setJustificationMode(int)

You can still use it but you will need to validate the OS Version before calling it. If you are already using Xamarin.Essentials (I guess you are) you can do something like this:

//Version 8.0 is API 26 (https://source.android.com/setup/start/build-numbers)

if (Xamarin.Essentials.DeviceInfo.Version.Major >= 8)
{
    if (Control != null)
    {
        Control.JustificationMode = JustificationMode.InterWord;
    }
}

Note: The validation will only prevent the crash but that means you will not be supporting devices with <8.0 (26) OS.

Hope this helps.-

I have tried with following code and it works in my local site:

public class CustomLabelRenderer: LabelRenderer
{
    public CustomLabelRenderer(Context context) : base(context)
    {

    }


    protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged(e);

        if (Xamarin.Essentials.DeviceInfo.Version.Major >= 8)
        {
            if (Control != null)
            {
                Control.SetBackgroundColor(Android.Graphics.Color.AliceBlue);
                Control.JustificationMode = JustificationMode.InterWord;
            }
        }
        else
        {
            if (Control != null)
            {
                Control.SetBackgroundColor(Android.Graphics.Color.Red);
                Control.TextAlignment = Android.Views.TextAlignment.Center;
            }
        }
    }
}

The effect on Android 9.0 device:

enter image description here

The effect on Android 7.0 device:

enter image description here

Related