【问题标题】:Android. TextView. Last visible character of the text安卓。文本视图。文本的最后一个可见字符
【发布时间】:2021-10-17 18:28:40
【问题描述】:

我有一个针对整个屏幕的 TextView 匹配,并在其上附加了一个文本。 例如,乌鸦诗:

Once upon a midnight dreary, while I pondered, weak and weary,
Over many a quaint and curious volume of forgotten lore,
While I nodded, nearly napping, suddenly there came a tapping,
As of some one gently rapping, rapping at my chamber door.
"'Tis some visiter," I muttered, "tapping at my chamber door—
Only this, and nothing more." etc etc etc...

我无法在手机屏幕上看到所有内容。 所以问题: 如何获取文本最后一个可见字符的索引? How can I see it

【问题讨论】:

  • 这可能已经在这里的某个地方得到了回答,但我找不到任何相关的东西,所以:drive.google.com/file/d/1r3-794zuR4qP-8uy6CARtZy8Mpq9c7cm/…。目前尚不清楚您想如何处理部分可见的线。该示例抓住了最后一条完全可见的线,但您可以根据需要进行调整。如果没有进一步测试,我不会尝试在 EditTexts 上使用它,但它应该在常规 TextViews 上运行良好。
  • 我忘了提到,如果空行是最后一个完全“可见”的行,它只会返回空格,因为也不清楚如何处理它。

标签: android string kotlin textview mobile-development


【解决方案1】:

如果你想要索引然后使用,

val poem = "hello"
val lastCharacterIndex = poem.toCharArray().size - 1

如果您想要该索引处的字符,请使用,

val character = poem.toCharArray()[index]

但我认为你想让你的文本视图可以滚动,这样你就可以看到整首诗。然后你可以使用 ScrollView 作为 XML 中的父标签,然后将文本视图包装在其中。

【讨论】:

  • 其实我希望 TextView 返回最后一个可见的字符索引(根本不是最后一个)。并且不应该使用 ScrollView。
  • @eyelog 最后一个可见字符?还是字符串?
  • OP 的问题很清楚,他/她想要最后一个可见字符而不是物理方式的最后一个字符。
  • textView.text 的最后一个可见字符的索引。 String 或 CharSequence - 没关系。
【解决方案2】:

非常感谢Mike M这里的答案:

fun TextView.getLastVisibleCharacter(): Int {
        val layoutBottom = height + scrollY - totalPaddingTop - totalPaddingBottom
        val bottomLine = layout.getLineForVertical(layoutBottom)
        val lastWhollyVisibleLineNumber =
            if (layout.getLineBottom(bottomLine) > layoutBottom) bottomLine - 1
            else bottomLine
        return layout.getLineVisibleEnd(lastWhollyVisibleLineNumber) - 1
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多