【问题标题】:How to determine the number of lines visible in TextView?如何确定 TextView 中可见的行数?
【发布时间】:2017-04-11 21:05:03
【问题描述】:

如何获取TextView 的可见部分显示了多少行?我使用文本,在每个屏幕分辨率上都没有完全放在TextView 中。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/logs_text"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</LinearLayout>

String s = "very big text"
TextView logText = (TextView) view.findViewById(R.id.logs_text);
logText.setText(s);     

【问题讨论】:

  • 你想设置 textview 有多少行,还是只获取他有多少行?
  • 改写问题
  • 使用 textviewobject.getText() 获取 textview 上设置的文本并与原始文本进行比较。
  • 我有人在谷歌上搜索它只是限制 TextView 中的行数然后设置 TextView 的 maxLinesellipsize 属性就足够了:例如android:maxLines="2" android:ellipsize="end"

标签: android textview lines


【解决方案1】:

android.text.Layout 包含此信息及更多信息。使用textView.getLayout().getLineCount()获取行数。

请注意,如果在布局过程完成之前调用 getLayout() 可能会返回 null。在onGlobalLayout()onPreDraw()ViewTreeObserver 之后调用getLayout()。例如

textView.getViewTreeObserver().addOnPreDrawListener(() -> {
    final int lineCount = textView.getLayout().getLineCount();
});

如果您只想要可见的行数,您可能应该使用以下答案中提到的方法:

Is there a way of retrieving a TextView's visible line count or range?

【讨论】:

  • 我在 textview 中看到 25 行,但是当我使用 getLineCount() 时,我在 logcat 中得到 152
  • 它返回布局中的行数,而不是布局中可见的行数。无论如何,您可以使用 Layout 来计算它们。很快就会更新答案。
  • 获取实际行数:int count = editView.getText().toString().split("\\r?\\n").length;
  • textView.getLayout() 正在返回 null
猜你喜欢
  • 1970-01-01
  • 2017-11-22
  • 2010-12-18
  • 2014-03-08
  • 1970-01-01
  • 2012-10-21
  • 2013-07-06
  • 2012-04-21
  • 1970-01-01
相关资源
最近更新 更多