Auto Scale TextView Text to Fit within Bounds

后端 未结 30 2923
囚心锁ツ
囚心锁ツ 2020-11-21 05:49

I\'m looking for an optimal way to resize wrapping text in a TextView so that it will fit within its getHeight and getWidth bounds. I\'m not simply looking for

30条回答
  •  我寻月下人不归
    2020-11-21 05:59

    Warning, bug in Android Honeycomb and Ice Cream Sandwich

    Androids versions: 3.1 - 4.04 have a bug, that setTextSize() inside of TextView works only for the 1st time (1st invocation).

    Bug is described here: http://code.google.com/p/android/issues/detail?id=22493 http://code.google.com/p/android/issues/detail?id=17343#c9

    workaround is to add new line character to text assigned to TextView before changing size:

    final String DOUBLE_BYTE_SPACE = "\u3000";
    textView.append(DOUBLE_BYTE_SPACE);
    

    I use it in my code as follow:

    final String DOUBLE_BYTE_SPACE = "\u3000";
    AutoResizeTextView textView = (AutoResizeTextView) view.findViewById(R.id.aTextView);
    String fixString = "";
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR1
       && android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {  
        fixString = DOUBLE_BYTE_SPACE;
    }
    textView.setText(fixString + "The text" + fixString);
    

    I add this "\u3000" character on left and right of my text, to keep it centered. If you have it aligned to left then append to the right only. Of course it can be also embedded with AutoResizeTextView widget, but I wanted to keep fix code outside.

提交回复
热议问题