-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFitTextView.java
More file actions
115 lines (74 loc) · 2.62 KB
/
FitTextView.java
File metadata and controls
115 lines (74 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package com.sukohi.lib;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
public class FitTextView extends TextView {
private float minTextSize = 10f;
private String viewText;
private Paint paint;
public FitTextView(Context context) {
super(context);
}
public FitTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setFitText(CharSequence text) {
setText(text);
paint = new Paint();
paint.setTextSize(getTextSize());
FontMetrics fontMetrics = paint.getFontMetrics();
int paddingHeight = getPaddingTop() + getPaddingBottom();
int viewHeight = (int) (Math.abs(fontMetrics.ascent) + Math.abs(fontMetrics.descent) + paddingHeight);
setHeight(viewHeight);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
fitText();
}
private void fitText() {
viewText = this.getText().toString();
if(viewText.equals("")) {
return;
}
paint = new Paint();
final int viewWidth = this.getWidth() - (getPaddingRight() + getPaddingLeft());
float textSize = getTextSize();
if(minTextSize >= textSize) {
textSize = minTextSize;
} else {
float textWidth;
for (float fitTextSize = textSize; fitTextSize > minTextSize; fitTextSize--) {
textWidth = getTextWidth(fitTextSize);
if(textWidth < viewWidth) {
textSize = fitTextSize;
break;
}
}
}
setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
invalidate();
}
private float getTextWidth(float textSize) {
paint.setTextSize(textSize);
return paint.measureText(viewText);
}
}
/*** Example
// xml
<com.sukohi.lib.FitTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="test text"
android:textColor="#000000"
android:textSize="25sp"
android:paddingRight="5dp"
android:paddingLeft="5dp"
android:gravity="center" />
// Java
FitTextView fitTextView = new FitTextView();
fitTextView.setFitText(text);
***/