I really needed something like that. I needed the width of the TextView half-fixed size, but the text always needed it. Since size doesn't matter much, I created a view that resizes the text to fit it.
import android.content.Context; import android.util.AttributeSet; import android.util.TypedValue; import android.widget.TextView; 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(); } 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); } 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(); } } private float getTextWidth() { return getPaint().measureText(getText().toString()); } }
source share