有一个特定的文本字符串,使用特定的字体和大小,TextView 中可以设置多少文本,以便TextView不需要滚动。我的意思是,在不需要滚动的情况下,可以适合多少文本在TextView中。 这类似于如何确定Android中TextView中适合多少文本?,但我找不到可行的解决方案。请帮忙。
有一个特定的文本字符串,使用特定的字体和大小,TextView 中可以设置多少文本,以便TextView不需要滚动。我的意思是,在不需要滚动的情况下,可以适合多少文本在TextView中。 这类似于如何确定Android中TextView中适合多少文本?,但我找不到可行的解决方案。请帮忙。
@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());
}
}
这只是我的一个快速头脑风暴:
我会扩展TextView
类,并覆盖onLayout()
方法,将字符串截取,只要测量高度大于computeHorizontalScrollRange()
。
我认为这个解决方案更好,因为: