Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextView with mixed languages

I have a TextView with 2 lines. first line rtl language (let's say hebrew), second line is ltr language (let's say english)

The View result is something like:

       אחת שתיים שלוש
one two three

what i want: align rtl in that case

       אחת שתיים שלוש
          one two three

I've tried using setTextDirection() with TEXT_DIRECTION_FIRST_STRONG but alas the results were the same. Also tried TEXT_ANY_RTL without success

myTextView.setTextDirection(View.TEXT_DIRECTION_FIRST_STRONG);

if i'm using TEXT_DIRECTION_RTL it's working as expected but this is not really a solution because most of the time the TextView will contain only one language.

Is this solvable?

--- UPDATE ---

How i'm populating the TextView

SpannableStringBuilder ssb = new SpannableStringBuilder(titleText);
int end = titlText.length();
ssb.append("\n").append(otheText);
ssb.setSpan(new AbsoluteSizeSpan(size), end, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(ssb);
like image 972
royB Avatar asked Nov 01 '22 07:11

royB


2 Answers

Why not just use two TextViews?

like image 75
Karim Varela Avatar answered Nov 12 '22 19:11

Karim Varela


I've managed to solve this problem using Character.getDirectionality.

The first char that is a directional char will signify the TextView direction

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static int getTextDirection(String text) {
    final int length = text.length();
    for (int i = 0; i < length; i++) {
        final char c = text.charAt(i);
        final byte directionality = Character.getDirectionality(c);

        if(directionality == Character.DIRECTIONALITY_LEFT_TO_RIGHT){
            return View.TEXT_DIRECTION_LTR;
        }
        else if(directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT){
            return View.TEXT_DIRECTION_RTL;
        }
    }

    return View.TEXT_DIRECTION_ANY_RTL;
}

and then:

textView.setTextDirection(textDirection);

I Strongly believe that TEXT_DIRECTION_FIRST_STRONG is supposed to do the exact same thing according to the docs. sadly it's not the case.

I'm not accepting my answer in hope that someone will suggest better solution

like image 40
royB Avatar answered Nov 12 '22 19:11

royB