Search code examples
javaandroidandroid-layoutandroid-edittextunderline

Underlined EditText not working well for some languages like Arabic ( Android - Java )


I am trying to have visible lines in an EditText. I am satisfied with the result that I got for EditText with English Text, but when I use some languages like "Arabic" the Arabic text goes a little bit below the underline with each new line. You can see the problem in the pictures below:

The code that I use for this is as what you see below:

public class UnderlinedEditText  extends androidx.appcompat.widget.AppCompatEditText {
    private final Rect mRect;
    public Paint mPaint;

    public UnderlinedEditText(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mRect = new Rect();
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.BLACK);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int height = getHeight();
        int line_height = getLineHeight();

        int count = height / line_height;
        if (getLineCount() > count){
            count = getLineCount();
        }

        Rect r = mRect;
        Paint paint = mPaint;
        int baseline = getLineBounds(0, r);

        for (int i = 0; i < count; i++) {

            canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
            baseline += getLineHeight();
        }

        super.onDraw(canvas);
    }

I have tried setElegantTextHeight(true) but there was no effect, I think the Arabic language has extra padding/height but I couldn't find a solution.

Can anyone help?


Solution

  • It is solved by using the next line of code:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            setFallbackLineSpacing(false);
        }
    

    The problem was that android use fallback line spacing automatically. Now everything is fine :)