Android多行TextView,检查文本是否适合,或检查TextView是否已满

Jam*_*mes 14 android textview android-layout

我有一个Android应用程序布局,其中包含一个多行TextView.当屏幕处于纵向方向时,TextView可以在横向模式下运行时显示不同长度的文本.此外,当在小屏幕上运行时,TextView可以在更大的屏幕上运行时显示不同长度的文本.

有什么方法可以检查文本是否适合或将被截断?或者有什么方法可以检查TextView是否已满?

问题是TextView可能包含不同数量的行,具体取决于它是横向,纵向,小屏幕,大屏幕等.

感谢您的意见,

最好的祝福,

詹姆士

whi*_*zle 11

这些答案对我来说效果不佳.这就是我最终做的事情

Paint measurePaint = new Paint(myTextView.getPaint());
float pWidth = measurePaint.measureText("This is my big long line of text. Will it fit in here?");
float labelWidth = myTextView.getWidth();
int maxLines = myTextView.getMaxLines();

while (labelWidth > 0 && pWidth/maxLines > labelWidth-20) {
    float textSize = measurePaint.getTextSize();
    measurePaint.setTextSize(textSize-1);
    pWidth = measurePaint.measureText("This is my big long line of text. Will it fit in here?");
    if (textSize < TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_SP, 7,
            getContext().getResources().getDisplayMetrics())) break;
}

myTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, measurePaint.getTextSize());
Run Code Online (Sandbox Code Playgroud)

我并不是说这会适用于所有情况,因为我肯定会在这里偷工减料,但一般的想法是用textview的绘画测量文本并继续缩小它直到它适合textview.


Jam*_*mes 8

我找到了一个"厚脸皮"的解决方案来解决在MULTILINE TextView中测量文本高度的问题: -

//Calculate the height of the text in the MULTILINE TextView
int textHeight = textView.getLineCount() * textView.getLineHeight();
if (textHeight > textViewHeight) {
    //Text is truncated because text height is taller than TextView height
} else {
    //Text not truncated because text height not taller than TextView height
}
Run Code Online (Sandbox Code Playgroud)

不过这个解决方案有一些警告: -

首先,关于getLineHeight(),文本中的标记可能导致单个行高于或高于此高度,并且布局可能包含额外的第一行或最后一行填充.请参阅http://developer.android.com/reference/android/widget/TextView.html#getLineHeight()

其次,应用程序需要以像素为单位计算TextView的实际高度,并且(在我的布局中)它可能不像textView.getHeight()那样简单,并且计算可能因布局而异.

我建议避免使用 LinearLayout,因为TextView的实际像素高度可能因文本内容而异.我正在使用RelativeLayout(请参阅http://pastebin.com/KPzw5LYd).

使用这个 RelativeLayout,我可以按如下方式计算我的 TextView高度: -

//Calculate the height of the TextView for layout "http://pastebin.com/KPzw5LYd"
int textViewHeight = layout1.getHeight() - button1.getHeight() - button2.getHeight();
Run Code Online (Sandbox Code Playgroud)

希望有所帮助,

问候,

詹姆士


MiS*_*Str 0

要检查多行(或不)TextView 是否会被截断,请查看这篇文章

或者,您是否考虑过使用滚动文本视图?(选取框).. 如果文本对于给定宽度来说太长,文本将在哪里滚动(水平、动画)?

下面是布局文件中的 TextView 示例,它具有以下一些特征:

<TextView
    android:id="@+id/sometextview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ellipsize="marquee"
    android:marqueeRepeatLimit="marquee_forever"
    android:singleLine="true"
    android:scrollHorizontally="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:freezesText="true"
    android:textColor="#808080"
    android:textSize="14sp"
    android:text="This is a long scrolling line of text.. (etc)"/>
Run Code Online (Sandbox Code Playgroud)