【发布时间】:2011-02-02 23:01:09
【问题描述】:
对于具有特定字体和大小的特定文本字符串,可以在 textview 中设置多少文本,以便 textview 不需要滚动。我的意思是 TextView 中可以容纳多少文本,而不需要滚动。 这类似于How do I determine how much text will fit in a TextView in Android?,但我找不到可行的解决方案。请帮忙。
【问题讨论】:
对于具有特定字体和大小的特定文本字符串,可以在 textview 中设置多少文本,以便 textview 不需要滚动。我的意思是 TextView 中可以容纳多少文本,而不需要滚动。 这类似于How do I determine how much text will fit in a TextView in Android?,但我找不到可行的解决方案。请帮忙。
【问题讨论】:
假设您已经在寻找其他选项并且没有简单的方法可以做到这一点,这里有一个理论上可行的(我没有测试过)hackish 方法。
创建一个扩展 TextView 的新类。然后,覆盖在 TextView 的内容更新后将调用的方法。可能有更好的方法可以使用,但对于这个例子,让我们试试 onDraw()。此方法将检查宽度并查看它是否需要能够滚动。如果是这样,它将修剪字符串并设置文本。它会循环执行此操作,直到不再需要滚动为止。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(getWidth() < computeHorizontalScrollRange()){
// Requires scrolling, the string is too long
// Do whatever you need to do to trim the string, you could also grab the remaining string and do something with it.
// Set the TextView to use the trimmed string.
}
}
您需要确保它没有进入无限循环并检查宽度是否为零。
您还可以查看各种android:ellipsize 选项。
【讨论】:
我实际上需要类似的东西。我需要一个 TextView 宽度为半固定大小,但文本始终需要适合其中。由于大小并不重要,我创建了一个视图来更改文本大小直到它适合。
import android.content.Context;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
/**
* The text inside this TextView will resize to fit.
* It will resize until it fits within the view and padding
*/
public class FitTextView extends TextView {
private float defaultSize = 12;
public FitTextView(Context context) {
super(context);
}
public FitTextView(Context context, AttributeSet attrs) {
super(context, attrs);
defaultSize = getTextSize();
}
public FitTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
defaultSize = getTextSize();
}
/**
* Set the default size. This size is set every time the
* view is resized.
* @param size
*/
public void setDefaultSize(float size) {
defaultSize = size;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
setTextSize(TypedValue.COMPLEX_UNIT_PX, defaultSize);
fitCharsInView();
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
public void setText(CharSequence text, BufferType type) {
fitCharsInView();
super.setText(text, type);
}
/**
* Decreases the text size until it fits inside the view
*/
public void fitCharsInView() {
int padding = getPaddingLeft() + getPaddingRight();
int viewWidth = getWidth() - padding;
float textWidth = getTextWidth();
int iKillInfite = 0;
int maxIteration = 10000;
while(textWidth > viewWidth && iKillInfite < maxIteration) {
iKillInfite++;
float textSize = getTextSize();
setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize-1);
textWidth = getTextWidth();
}
}
/**
* Gets the width in pixels of the text
* @return
*/
private float getTextWidth() {
return getPaint().measureText(getText().toString());
}
}
【讨论】:
这只是我的一个快速头脑风暴:
【讨论】:
只要测量的高度大于computeHorizontalScrollRange(),我会扩展TextView 类并覆盖onLayout() 方法来修剪字符串。
我相信解决方案会更好一些,因为:
【讨论】: