修改系统文字大小后不改变android字体大小,自定义缩放

在BaseActivity或所需要的Activity中重写 getResources()

override fun getResources(): Resources {
        val resources = super.getResources()
        val configContext = createConfigurationContext(resources.configuration)

        return configContext.resources.apply {
            configuration.fontScale = 1.0f
            displayMetrics.scaledDensity = displayMetrics.density * configuration.fontScale
        }
    }


override fun attachBaseContext(newBase: Context) {
        val fontScale = SPUtils.getFloat("FONT_SCALE")
        ELog.d(TAG, "attachBaseContext: fontScale=$fontScale")
        val config = newBase.resources.configuration
        config.fontScale = fontScale
        val context = newBase.createConfigurationContext(config)
        super.attachBaseContext(context)
    }
可以通过继承EditText类来实现自动缩放字体大小的功能,具体实现步骤如下: 1. 创建一个自定义的EditText类,继承自EditText。 ```java public class AutoResizeEditText extends EditText { public AutoResizeEditText(Context context) { super(context); } public AutoResizeEditText(Context context, AttributeSet attrs) { super(context, attrs); } public AutoResizeEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } } ``` 2. 在该类中重写setText()方法,在该方法中调用resizeText()方法,实现自动缩放字体大小的功能。 ```java @Override public void setText(CharSequence text, BufferType type) { super.setText(text, type); resizeText(); } private void resizeText() { int viewWidth = getWidth() - getPaddingLeft() - getPaddingRight(); int viewHeight = getHeight() - getPaddingTop() - getPaddingBottom(); float textSize = getTextSize(); if (viewWidth <= 0 || viewHeight <= 0 || textSize <= 0) { return; } String text = getText().toString(); TextPaint textPaint = getPaint(); Rect bounds = new Rect(); textPaint.getTextBounds(text, 0, text.length(), bounds); float desiredTextSize = textSize * viewWidth / bounds.width(); if (desiredTextSize > textSize) { setTextSize(TypedValue.COMPLEX_UNIT_PX, Math.min(desiredTextSize, viewHeight)); } } ``` 3. 在布局文件中使用该自定义EditText。 ```xml <com.example.AutoResizeEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Hello, world!" android:padding="16dp"/> ``` 这样,当EditText的宽度发生变化时,setText()方法会被调用,从而自动缩放字体大小,保证文本可以完整显示在EditText中。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值