您的位置:首页 > 其它

重写TextView解决HorizontalScrollView中TextView显示不全的问题

2017-09-13 15:31 501 查看
/**
* 适用于宽度相对确定的情况
* Created by xieyuhai on 2017/9/13.
*/

public class MyTextView extends AppCompatTextView {

private static final String TAG = "MyTextView";

public MyTextView(Context context) {
this(context, null);
}

public MyTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}

@Override
protected void onFinishInflate() {
super.onFinishInflate();

Log.e(TAG, "onFinishInflate: w:" + getWidth() + "; height:" + getHeight());
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);

float textWidth = getPaint().measureText(getText().toString());

BigDecimal v1 = new BigDecimal(Double.toString(textWidth));
BigDecimal v2 = new BigDecimal(Double.toString(w));

//一行的高度*总行数+上下内边距= 控件的高度             避免死循环,保留两位小数,考虑到精度可能会丢失,在后面加1
BigDecimal lineCount = v1.divide(v2, 2, BigDecimal.ROUND_HALF_EVEN).add(new BigDecimal(1));

Paint.FontMetrics fm = getPaint().getFontMetrics();
double v = Math.ceil(fm.descent - fm.ascent);//
//一行的高度*总行数+上下内边距= 控件的高度
setHeight((int) (v * lineCount.doubleValue()) + getPaddingTop() + getPaddingBottom()); }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: