Android: How to wrap text by chars? (Not by words)

核能气质少年 提交于 2019-11-28 17:38:28

It's a bit hacky, but you could replace spaces with the unicode no-break space character (U+00A0). This will cause your text to be treated as a single string and wrap on characters instead of words.

myString.replace(" ", "\u00A0");

Olsavage

As I know, there is no such property for TextView. If you want to implement text wrapping by yourself, you can override TextView and use Paint's breakText(String text, boolean measureForwards, float maxWidth, float[] measuredWidth) function. Note that you have to specify text size, typeface etc to Paint instance.

Add an invisible zero-width space ('\u200b') after each character:

textView.setText(longlongText.replaceAll(".(?!$)", "$0\u200b"));

This works also for long strings containing no spaces (for example, link addresses). Standard TextView tries to break a link by question mark '?' and slash '/'.

public class CharacterWrapTextView extends TextView {
  public CharacterWrapTextView(Context context) {
    super(context);
  }

  public CharacterWrapTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public CharacterWrapTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }

  @Override public void setText(CharSequence text, BufferType type) {
    super.setText(text.toString().replace(" ", "\u00A0"), type);
  }
}

<com.my.CharacterWrapTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text"/>

(yellow background: normal textview)

The following extension method implements @atarasenko's solution in C# which may be useful for people working with Xamarin.Android. The resultant string will wrap within a TextView character-by-character.

/// <summary>
/// Add zero-width spaces after each character. This is useful when breaking text by
/// character rather than word within a TextView.
/// </summary>
/// <param name="value">String to add zero-width spaces to.</param>
/// <returns>A new string instance containing zero-width spaces.</returns>
public static string AddZeroWidthSpaces(this string value) => Regex.Replace(
    value
    , "."
    , "$0\u200b"
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!