Created
November 22, 2016 13:06
-
-
Save cab404/7b8a4217d731894f9ee5deabed59532b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context; | |
import android.graphics.Canvas; | |
import android.util.AttributeSet; | |
import android.widget.TextView; | |
/** | |
* Width resizing text view | |
* | |
* @author cab404 | |
*/ | |
public class WidthResizeTextView extends TextView { | |
public WidthResizeTextView(Context context) { | |
super(context); | |
} | |
public WidthResizeTextView(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
} | |
public WidthResizeTextView(Context context, AttributeSet attrs, int defStyleAttr) { | |
super(context, attrs, defStyleAttr); | |
} | |
{ | |
setSingleLine(); | |
} | |
float lastWidth, lastCalculatedSize; | |
@Override | |
protected void onDraw(Canvas canvas) { | |
super.onDraw(canvas); | |
int viewWidth = getWidth(); | |
float top = viewWidth, bottom = 0, width = 0, current = 0; | |
int spec = MeasureSpec.makeMeasureSpec(1000000, MeasureSpec.AT_MOST); | |
int steps = 300; | |
if (viewWidth != lastWidth) { | |
while (Math.abs(width - viewWidth) > 5f && steps-- > 0) { | |
current = (top + bottom) / 2; | |
setTextSize(current); | |
measure(spec, spec); | |
width = getMeasuredWidth(); | |
if (width - viewWidth < 0) | |
bottom = (top - bottom) / 2 + bottom; | |
if (width - viewWidth > 0) | |
top = top - (top - bottom) / 2; | |
} | |
lastWidth = viewWidth; | |
lastCalculatedSize = current; | |
} else { | |
current = lastCalculatedSize; | |
} | |
setTextSize(current); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment