Android 動態改變TextView字型大小
阿新 • • 發佈:2019-01-08
package view.myview; import android.content.Context; import android.util.AttributeSet; import android.widget.TextView; import control.other.PxDpSp; /** * @類名:ChangedSizeTextView * @功能描述:動態改變字型大小:根據控制元件的大小,自動改變字型大小,保證部分字型不會無法顯示 * @作者:XuanKe'Huang * @時間:2014-10-22 下午8:39:15 * @Copyright 2014 */ public class ChangedSizeTextView extends TextView { public ChangedSizeTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } public ChangedSizeTextView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public ChangedSizeTextView(Context context) { super(context); init(context); } /** * 方法名: init * * 功能描述:初始化 * * @param context * 上下文物件 * @return void * * </br>throws */ private void init(Context context) { this.context = context; } private Context context; /** * 方法名: changedSize * * 功能描述:動態改變字型大小 * * @return void * * </br>throws */ private void changedSize() { if (this.getText().toString().length() >= 10) {// 如果字數大於10,則設定為單行 this.setSingleLine(); return; } int textPx = PxDpSp.sp2px(context, this.getTextSize());// 得到字型的大小 if (textPx > this.getWidth()) {// 判斷字型的大小是否超過控制元件的大小 this.setTextSize(PxDpSp.px2sp(context, this.getWidth() - 20));// 如果超過,則根據控制元件的大小設定字型的大小 } if (textPx > this.getHeight()) { this.setTextSize(PxDpSp.px2sp(context, this.getHeight() - 20));// 如果超過,則根據控制元件的大小設定字型的大小 } } @Override public void setText(CharSequence text, BufferType type) { super.setText(text, type); changedSize(); } }