【问题标题】:Custom TextInputLayout class, extra top margin when used in layout files自定义 TextInputLayout 类,在布局文件中使用时有额外的上边距
【发布时间】:2021-08-07 11:45:49
【问题描述】:

在创建自定义 TextInputLayout 视图类时,自定义类的布局文件看起来很正常,但在活动/片段布局文件中使用时,视图会增加一些顶部边距,我不明白为什么。

这是自定义视图布局文件:

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.textfield.TextInputLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text_input_layout"
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="My Custom TextInputLayout">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/edit_text_date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</com.google.android.material.textfield.TextInputLayout>

当我检查这个自定义布局文件的设计预览时,它看起来很正常,只有很小的浮动提示边距:

下面是自定义视图类(我在类中使用ViewBinding,虽然我认为这与问题无关,但还是以常规inflate()出现):

class CustomTextInputLayout(context: Context, attrs: AttributeSet): TextInputLayout(context, attrs) {

    val binding: CustomTextInputLayoutBinding = CustomTextInputLayoutBinding.inflate(LayoutInflater.from(context), this, true)

}

因此,所有设置完成后,我将在 Activity 布局中使用它,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.vinnorman.customtextfieldtesting.CustomTextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

但是,当我运行该应用程序并在 activity_main.xml 设计预览中看到它时,它的上边距增加了很多:

关于为什么会有这个额外的上边距以及如何摆脱它的任何想法?

【问题讨论】:

  • 这可能是因为一旦您开始输入,它就会留下足够的空间来显示提示。 Afaik,TextInputLayout 将提示平滑地移向EditText 的顶部。您可以通过使用hintEnabled=false 并删除提示来测试这一点
  • 恐怕这不是问题所在。在第一个屏幕截图中,提示有正确的空间量,在第二个屏幕截图中它增加了很多。禁用提示会删除第一个屏幕截图中的微小边距,并在第二个屏幕截图中略微减少额外的空间,但仍然可能有 12dp 左右的额外边距,无论是否有提示。

标签: android xml android-layout


【解决方案1】:

如果您在布局检查器中查看您的布局,您会发现您有一个 TextInputLayout 嵌入在另一个 TextInputLayout 中。这是因为您的自定义视图本身就是一个 TextInputLayout 并且您从您的布局中将另一个 TextInputLayout 膨胀到其中。您在 Android Studio 设计器中看不到这一点,而只能在设备/模拟器上看到。

解决方法是使用merge 标签。详情请见Use the <merge> tag

【讨论】:

  • 完美,对我制作自定义类的方式有误解。它们在扩展的 View 类“内部”膨胀。我对修复真的很懒惰,只是扩展了一个 FrameLayout 来修复它!
猜你喜欢
  • 2017-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-05
  • 2020-02-11
  • 2019-01-28
  • 2013-08-15
  • 1970-01-01
相关资源
最近更新 更多