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

Android自定义EditTextCarded:内嵌EditText不显示问题求助

问题排查与解决方案

嘿,我来帮你搞定这个EditText不显示的问题!你遇到的情况主要有几个核心原因,咱们一个个拆解修复:

1. LayoutParams类型不匹配

你给EditText设置的是LinearLayout.LayoutParams,但EditText的父容器是CardView(它继承自FrameLayout)。虽然ViewGroup的LayoutParams有一定兼容性,但使用错误的父容器LayoutParams类型,可能导致布局参数不被系统正确识别,直接让EditText无法正常布局显示。

修复方法:改用FrameLayout.LayoutParams(或者直接用CardView.LayoutParams,二者完全兼容):

editText.layoutParams = FrameLayout.LayoutParams(
    ViewGroup.LayoutParams.MATCH_PARENT, 
    ViewGroup.LayoutParams.MATCH_PARENT
)

2. onMeasure方法未正确实现

你重写了onMeasure但只留了....,如果没有调用super.onMeasure(widthMeasureSpec, heightMeasureSpec),CardView就不会自动测量它的子View(也就是你的EditText),这会导致EditText的尺寸被计算为0,自然就看不到了。

修复方法:要么在onMeasure里调用父类实现,让系统正常处理子View测量;要么如果不需要自定义测量逻辑,直接删掉这个重写方法就行:

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    // 如果你有自定义测量逻辑,写在这里
    super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}

3. 布局高度设置过小

你在XML里给EditTextCarded设置的高度是30dp,这个高度实在太小了——EditText默认有内边距,加上文字本身的高度,很可能导致EditText被完全裁剪或者显示不全。

修复方法:把高度调大,比如改成wrap_content或者60dp:

<com.example.groot.edittext_carded.EditTextCarded
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"/>

完整修复后的代码示例

Kotlin自定义View代码

class EditTextCarded @JvmOverloads
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int = 0) : CardView(context, attrs, defStyleAttr) {

    init {
        val editText = EditText(context)
        // 使用正确的LayoutParams类型
        editText.layoutParams = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        // 给EditText加内边距,避免文字贴在CardView边缘
        editText.setPadding(16, 16, 16, 16)
        editText.hint = "Test"
        addView(editText)
    }

    // 不需要自定义测量的话,直接删掉这个方法即可
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }
}

XML布局代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="#eee"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.groot.edittext_carded.MainActivity">

    <com.example.groot.edittext_carded.EditTextCarded
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"/>
</LinearLayout>

内容的提问来源于stack exchange,提问作者Cyrus the Great

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:17:19