在android Edittext中实现autoSizeTextType

时间:2017-09-25 13:43:29

标签: android text android-edittext resize autoresize

Android Oreo buildToolsVersion提供了一种在AppCompatTextView中自动调整textize的简化方法,如下所示

<android.support.v7.widget.AppCompatTextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="50dp"
    android:maxWidth="300dp"
    android:background="@android:color/holo_green_light"
    app:autoSizeTextType="uniform"
    app:autoSizeMinTextSize="5sp"
    app:autoSizeMaxTextSize="50sp"
    app:autoSizeStepGranularity="4sp"
    />

类似的实现是否可以应用于AppCompatEditText,因为它基本上是TextView的扩展?简单地将autoSizeTextType应用于AppCompatEditText似乎不起作用。有没有办法让这项工作成功?

3 个答案:

答案 0 :(得分:2)

不,你不能。请参阅here;它对所有AppCompatEditText都禁用,因为它不受支持。

答案 1 :(得分:2)

我有一个特定的案例,它是一行EditText,所以我发布我的解决方案是为了对某人有所帮助...

private val initialTextSize: Float by lazy {
    resources.getDimensionPixelSize(R.dimen.default_text_size).toFloat()
}

private fun updateTextSize(s: CharSequence) {
    // Auto resizing text
    val editWidth = myEditText.width
    if (editWidth > 0) { // when the screen is opened, the width is zero
        var textWidth = myEditText.paint.measureText(s, 0, s.length)
        if (textWidth > editWidth) {
            var fontSize = initialTextSize
            while (textWidth > editWidth && fontSize > 12) { // minFontSize=12
                fontSize -= 1
                myEditText.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize)
                textWidth = myEditText.paint.measureText(s, 0, s.length)
            }
        // As long the text grows, the font size decreases, 
        // so here I'm increasing it to set the correct text s
        } else {
            var fontSize = myEditText.textSize
            while (textWidth <= editWidth && fontSize < initialTextSize) {
                fontSize = min(fontSize + 1, initialTextSize)
                myEditText.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize)
                textWidth = myEditText.paint.measureText(s, 0, s.length)
            }
        }
    }
}

然后,您必须从附加到TextWatcher的{​​{1}}调用此函数。

EditText

答案 2 :(得分:0)