【问题标题】:Android TextVIew Ellipsis based on view sizeAndroid TextVIew Ellipsis 基于视图大小
【发布时间】:2015-11-05 16:45:57
【问题描述】:

如果文本太长,我正在尝试将省略号设置为文本的末尾(多行)。

我已经知道我可以使用setMaxLines()setEllipsize()来达到这个效果。但是,由于我的 textview 的大小是动态变化的,我不知道可以显示的最大行数。相反,我有 textview 的高度(按像素)。

如何根据视图的高度和文本(包括字体属性)设置省略号?如果没有我可以使用的直接可用资源,那么最简单的方法是什么?

【问题讨论】:

    标签: android textview ellipsis


    【解决方案1】:

    您可以使用getLineCount()(但只能在布局通过之后)。

    更多信息请参见this answer

    【讨论】:

    • getLineCount() 将不起作用,因为 textview 可能会从小高度增长到大高度。如果我在高度较小时设置最大行数,getLineCount 将始终在高度增加时返回旧的小数。所以最大行号不会更新。此外,设置最大行数会安排布局通道,这不是我的愿望。不过还是谢谢你的回答。
    【解决方案2】:

    我已经使用this answer 的概念实现了这一点。

    你可以像这样创建一个扩展函数-

    /**
     * Calculate max lines according height
     *
     * @param text- text need to be set
     * @param lineCount- invoked with -1 if view height is enough to show full text,
     *                   otherwise invoked with maxLines
     */
    inline fun TextView.calculateMaxLines(text: String, crossinline lineCount: (Int) -> (Unit)) {
        val params: PrecomputedTextCompat.Params = TextViewCompat.getTextMetricsParams(this)
        val ref: WeakReference<TextView>? = WeakReference(this)
        GlobalScope.launch(Dispatchers.Default) {
            val computedText = PrecomputedTextCompat.create(text, params)
            ref?.get()?.apply {
                TextViewCompat.setPrecomputedText(this, computedText)
                GlobalScope.launch(Dispatchers.Main) {
                    ref.get()?.let {
                        val bounds = it.getLineBounds(0, null)
                        val heightRequired = bounds * it.lineCount
                        val maxLines = if (heightRequired > height) {
                            height / bounds
                        } else -1
                        lineCount.invoke(maxLines)
                    }
                }
            }
        }
    }
    

    然后你可以调用它并像这样设置 maxLines-

    textView.calculateMaxLines("Line 1\nLine2\nLine3\nLine4\nLine5\nLine6\nLine7\nLine8") {
                if (it >= 0) {
                    tvUserName.maxLines = it
                    tvUserName.ellipsize = TextUtils.TruncateAt.END
                }
            }
    

    或者,对于Java,您可以这样称呼它-

    ExtensionsKt.calculateMaxLines(textView, text, maxLines -> {
                if (maxLines >= 0) {
                    textView.setMaxLines(maxLines);
                    textView.setEllipsize(TextUtils.TruncateAt.END);
                }
                return null;
            });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-18
      • 2013-09-19
      • 2013-09-28
      • 1970-01-01
      相关资源
      最近更新 更多