android弹性按钮(字的多少改变,button大小改变)

327 阅读1分钟

自定义view

/**
 *
 * 字体大小自适应按钮宽度的按钮
 * 如果需要动态变化可以调用invalidate()方法来触发onDraw()重绘
 * @author wy
 */
public class AutofitButton extends AppCompatButton {

    public AutofitButton(Context context) {
        super(context);
        init(context, null);
    }

    public AutofitButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {


    }

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

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        autoFitTextSize();
    }

    /**
     * 计算fontSize通过text、width、padding
     */
    private void autoFitTextSize() {
        Paint p = getPaint();
        p.setTypeface(getTypeface());
        p.setTextSize(getTextSize());
        float needWidth = getPaddingLeft() + getPaddingRight() + p.measureText(getText().toString());
//        Log.e("autofitbutton", needWidth + "," + needWidth / getWidth() + "," + getTextSize());
//这里是为了防止一个按钮时,按钮内字体过大
        if (needWidth > getWidth())
//Math.floor是为了防止算出的值有小数导致绘画的字体闪烁
            setTextSize(TypedValue.COMPLEX_UNIT_PX, (float) Math.floor(getTextSize() * (getWidth() / needWidth)));
    }
}

使用

 <com.example.myapplication.AutofitButton
        android:id="@+id/autofitbutton"
        android:onClick="select"
        android:paddingTop="8dp"
        android:paddingBottom="8dp"
        android:paddingLeft="19dp"
        android:paddingRight="19dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>