--------- 代码
① 注意: TextView一定指定宽度,在执行getTextSize方法之前,否则有问题。
② 参考思路
http://www.voidcn.com/blog/u013780605/article/p-6140826.html
传送门 点击打开链接
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
private EditText editText;
private int count;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initListener();
}
private void initView() {
editText = (EditText) findViewById(R.id.edittext);
mTextView = (TextView) findViewById(R.id.textview1);
}
private void initListener() {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String s1 = s.toString();
mTextView.setText(s1);
//设置计算好的字体大小
int widthPixels = getResources().getDisplayMetrics().widthPixels;
mTextView.setTextSize(getTextSize(mTextView, widthPixels, s1));
}
});
}
/**
* 计算textSize
*
* @param textView
* @param width textview的宽度
* @param str
* @return textSize
*/
public float getTextSize(TextView textView, int width, String str) {
//字符最大的大小
float defaultSize = 30.0f;
for (; ; ) {
mTextView.setTextSize(defaultSize);
Paint paint = mTextView.getPaint();
float wm = paint.measureText(str);
Log.i("adjust", "getTextSize: count = " + count++);
if (wm <= width)
break;
else
//每次减小的步长
defaultSize -= 0.1;
}
return defaultSize;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.adnonstop.autoscaletextview.MainActivity">
<TextView
android:id="@+id/textview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorAccent"
android:gravity="center_vertical" />
<EditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="@color/colorPrimary"
android:hint="123" />
</LinearLayout>
------- 运行结果展示
--->补充setTextSize的坑点:
void setTextSize(int unit, float size)
Set the default text size to a given unit and value.
void setTextSize(float size)
Set the default text size to the given value, interpreted as "scaled pixel" units.
想以px作为单位setTextSize,必须调用textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,像素值);