当前位置:   article > 正文

textview的分行显示_安卓实现两个textview分行

安卓实现两个textview分行

第一种是

  1. <TextView
  2. android:id="@+id/tv_servicequality"
  3. android:layout_width="wrap_content"
  4. android:layout_height="wrap_content"
  5. android:text="谢谢乘坐\n请对本次服务评价"
  6. android:textSize="45dp"/>
或者自己自定义TextView,代码如下:

  1. import android.content.Context;
  2. import android.graphics.Paint;
  3. import android.text.TextUtils;
  4. import android.util.AttributeSet;
  5. import android.widget.TextView;
  6. /**
  7. * Created by Administrator on 2016/10/13.
  8. */
  9. public class AutoSplitTextView extends TextView{
  10. private boolean mEnabled = true;
  11. public AutoSplitTextView(Context context) {
  12. super(context);
  13. }
  14. public AutoSplitTextView(Context context, AttributeSet attrs) {
  15. super(context, attrs);
  16. }
  17. public AutoSplitTextView(Context context, AttributeSet attrs, int defStyle) {
  18. super(context, attrs, defStyle);
  19. }
  20. public void setAutoSplitEnabled(boolean enabled) {
  21. mEnabled = enabled;
  22. }
  23. @Override
  24. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  25. if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
  26. && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY
  27. && getWidth() > 0 && getHeight() > 0 && mEnabled) {
  28. String newText = autoSplitText(this);
  29. if (!TextUtils.isEmpty(newText)) {
  30. setText(newText);
  31. }
  32. }
  33. super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  34. }
  35. private String autoSplitText(final TextView tv) {
  36. final String rawText = tv.getText().toString(); //原始文本
  37. final Paint tvPaint = tv.getPaint(); //paint,包含字体等信息
  38. final float tvWidth = tv.getWidth() - tv.getPaddingLeft() - tv.getPaddingRight(); //控件可用宽度
  39. //将原始文本按行拆分
  40. String [] rawTextLines = rawText.replaceAll("\r", "").split("\n");
  41. StringBuilder sbNewText = new StringBuilder();
  42. for (String rawTextLine : rawTextLines) {
  43. if (tvPaint.measureText(rawTextLine) <= tvWidth) {
  44. //如果整行宽度在控件可用宽度之内,就不处理了
  45. sbNewText.append(rawTextLine);
  46. } else {
  47. //如果整行宽度超过控件可用宽度,则按字符测量,在超过可用宽度的前一个字符处手动换行
  48. float lineWidth = 0;
  49. for (int cnt = 0; cnt != rawTextLine.length(); ++cnt) {
  50. char ch = rawTextLine.charAt(cnt);
  51. lineWidth += tvPaint.measureText(String.valueOf(ch));
  52. if (lineWidth <= tvWidth) {
  53. sbNewText.append(ch);
  54. } else {
  55. sbNewText.append("\n");
  56. lineWidth = 0;
  57. --cnt;
  58. }
  59. }
  60. }
  61. sbNewText.append("\n");
  62. }
  63. //把结尾多余的\n去掉
  64. if (!rawText.endsWith("\n")) {
  65. sbNewText.deleteCharAt(sbNewText.length() - 1);
  66. }
  67. return sbNewText.toString();
  68. }
  69. }




声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/242705
推荐阅读
相关标签
  

闽ICP备14008679号