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

╄→гoц情女王★ 提交于 2020-01-28 03:35:35

问题


For instance:

This is foo text for wrapping text in TextView

The way that TextView wraps is:

This is foo text for
wrapping text in ...

I want this:

This is foo text for wr
apping text in TextView

回答1:


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");




回答2:


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.




回答3:


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 '/'.




回答4:


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)




回答5:


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"
);


来源:https://stackoverflow.com/questions/5118367/android-how-to-wrap-text-by-chars-not-by-words

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!