避免在URL上进行音节化

时间:2014-03-12 11:36:58

标签: java android string text word-wrap

我试图显示这样的文字:

"For more infomration please visit www.my-site.com"

对于某些分辨率/屏幕,文本显示为:

|For more information please visit www.my- |
|site.com                                  |

我可以在网址部分避免这种影响吗?

3 个答案:

答案 0 :(得分:1)

如果此文本出现在标准的活动或片段中,您可以将其拆分为两个TextView,第一个包含信息文本,第二个包含网站URL并设置属性android:singleLine="true"以保持文本内部被包裹。

接下来,您可以将这两个TextView并排放置在自定义“FlowLayout”中,如果可能,它将在一行显示:

|For more information please visit www.my-site.com |  
|                                                  |

或包裹在TextView边界:

|For more information please visit        |  
|www.my-site.com                          |

不幸的是,Android中没有本机FlowLayout。您可以自己编写,调整像RelativeLayout这样的内容,编写自定义方法来测量屏幕宽度和子视图(有关如何完成此操作的示例,请参阅How to write Android Autowrap Layout using RelativeLayoutLinearLayout Horizontal with wrapping children)。

或者,您可以使用几个已经可用的布局:

答案 1 :(得分:1)

如果您的项目要求不允许您使用换行符或自定义" FlowLayout"布局类型,您可以通过使用自定义方法扩展TextView来创建自定义视图,以应用自定义换行方案。

// String text must contain a portion between
//   <unwrappable></unwrappable> tags.
public void setCustomWrappedText(String text) {
    final String OPEN_TAG = "<unwrappable>";
    final String CLOSE_TAG = "</unwrappable>";

    // Unwrappable string not yet set, find it, between <unwrappable></unwrappable>
    // tags, strip out the tags, and set prefix and suffix.
    int index = text.indexOf(OPEN_TAG);
    int index2 = text.indexOf(CLOSE_TAG);
    String prefix = text.substring(0, index);
    String unwrappable = text.substring(index + OPEN_TAG.length(), index2);
    String suffix = text.substring(index2 + CLOSE_TAG.length());

    // Contents already fit on one line, do nothing.
    this.setText(prefix + unwrappable + suffix);
    int lines = this.getLineCount();
    if (lines < 2)
        return;

    // Set content prefix, ie. text _before_ unwrappable appears, and count lines.
    this.setText(prefix);
    lines = this.getLineCount();

    // Set content to prefix _with_ unwrappable (no suffix), and count lines.
    this.setText(prefix + unwrappable);

    if (this.getLineCount() > lines) // Text has wrapped inside unwrappable, insert a line break to prevent.
        this.setText(prefix + "\n" + this.unwrappable + suffix);
    else // Text may or may not wrap _after_ unwrappable, we don't care.
        this.setText(prefix + this.unwrappable + suffix);
}

答案 2 :(得分:1)

使用non-breaking hyphen代替常规-

在XML中:&#x2011;

在Java中:"\u2011"

当然,如果您有可点击的链接,请不要在网址中替换它,而只是替换链接文字。

示例:

<TextView android:layout_width="60dp" android:layout_height="wrap_content"
    android:text="foo foo-foo foo&#x2011;foo"/>

图形布局:

enter image description here

相关问题