You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Multiline TextInputEditText设置wrap_content后无法恢复初始尺寸求助

解决TextInputEditText清空文本后高度无法恢复的问题

针对TextInputEditText设置textMultiLine="true"和layout_height="wrap_content"后,清空文本高度无法回退到初始状态的问题,以下是几个实用的解决思路:

方法1:强制触发布局重绘

单纯修改layoutParams.height为WRAP_CONTENT不会立即生效,需要主动请求View重新计算布局。清空文本后执行以下代码:

// Kotlin示例
editText.text = null
editText.layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
editText.requestLayout() // 关键步骤:强制更新布局

Java版本:

// Java示例
editText.setText(null);
ViewGroup.LayoutParams params = editText.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
editText.setLayoutParams(params);
editText.requestLayout();

如果控件嵌套在TextInputLayout中,可能需要同时对父布局调用requestLayout()。

方法2:自定义TextInputEditText重写文本变化逻辑

通过自定义控件,在文本清空时自动重置高度:

class AutoResizeTextInputEditText @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = com.google.android.material.R.attr.textInputEditTextStyle
) : TextInputEditText(context, attrs, defStyleAttr) {

    override fun onTextChanged(
        text: CharSequence?,
        start: Int,
        lengthBefore: Int,
        lengthAfter: Int
    ) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter)
        if (text.isNullOrEmpty()) {
            layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
            requestLayout()
        }
    }
}

XML布局中直接使用该自定义控件即可,无需额外代码处理。

方法3:用TextWatcher监听文本变化

如果不想自定义控件,可给原生控件添加文本监听:

editText.addTextChangedListener(object : TextWatcher {
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        if (s.isNullOrEmpty()) {
            editText.layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
            editText.requestLayout()
        }
    }

    override fun afterTextChanged(s: Editable?) {}
})

这种方式灵活,适合仅在特定页面处理的场景。

注意事项

  • 若控件嵌套在TextInputLayout中,需确保父布局TextInputLayout的layout_height也设为wrap_content,否则父布局的固定高度会限制子View的高度调整。
  • 可增加状态判断,仅当文本从非空变为空时才执行重置逻辑,避免频繁调用requestLayout()影响性能。

内容的提问来源于stack exchange,提问作者Al Sh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 10:58:17