【发布时间】: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