【问题标题】:Ellipsize TextView at the end of the word字尾的Ellipsize TextView
【发布时间】:2015-05-02 11:31:43
【问题描述】:

我正在使用TextViewandroid:ellipsize 属性和android:maxLines 使文本适合最多3 行。

问题是有时文本会在单词中间被剪切。我只想在单词末尾省略文本。例如:

Android 很棒

现在看起来像这样:

Android 令人敬畏...

但我希望它看起来像这样:

Android 是...

此外,用户可以在这个TextView 中动态更改textSize,因此很难预测哪个单词会是最后一个单词。

有没有办法只在全词末尾省略号?如果系统不允许这样做,是否有任何库可以提供此类功能,或者唯一的可能性是编写我自己的类来执行此操作?

【问题讨论】:

  • 1.获取您的文字大小; 2.获取您的文本视图大小; 3. 使用数学; 4. 对您的文本进行适当的更改
  • @MocialovBoris 你还没有回答我的问题。我有一个关于如何让我自己的类实现所需功能的想法,但我想了解一些现有的解决方案,我可以使用这些解决方案来节省我的时间。
  • 这不是试图回答您的问题,而是描述解决您问题的一种方法的评论。

标签: android android-layout textview


【解决方案1】:

您必须将 ellipsize 指定为 textview 的“end”。然后设置文本后,将 globallayout 监听器添加到 textview 并更改其文本如下:

TextView articleTitle = (TextView) v.findViewById(R.id.articleTitle);
        articleTitle.setText("This is a big big text");
        doEllipse(articleTitle);




 public void doEllipse(final TextView tv) {
    tv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
           tv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
           String text = tv.getLayout().getText().toString();
           int text1Index = text.indexOf("…");
           if (text1Index > 0) {
               text = text.substring(0, text.lastIndexOf(" ")) + "...";
               tv.setText(text);
           }    
        }
    });

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-17
    • 2017-12-31
    • 2012-06-30
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    相关资源
    最近更新 更多