Android 自定义TextInputLayout类,在布局文件中使用时额外的上边距
创建自定义Android 自定义TextInputLayout类,在布局文件中使用时额外的上边距,android,xml,android-layout,Android,Xml,Android Layout,创建自定义TextInputLayout视图类时,自定义类的布局文件看起来很正常,但在活动/片段布局文件中使用时,视图会添加一些额外的上边距,我不明白为什么 以下是自定义视图布局文件: <?xml version="1.0" encoding="utf-8"?> <com.google.android.material.textfield.TextInputLayout xmlns:android="http://schemas
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>
所有这些都设置好后,我将在活动布局中使用它,如下所示:
<?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设计预览中看到它时,它会增加很多页边空白:
关于为什么会有这个额外的上边距,以及如何消除它,您有什么想法吗?如果您在布局检查器中查看您的布局,您将看到您在另一个TextInputLayout中嵌入了一个TextInputLayout。这是因为您的自定义视图本身就是一个TextInputLayout,您可以将另一个TextInputLayout从布局充气到其中。在Android Studio designer中看不到这一点,但只能在设备/模拟器上看到
解决方法是使用
merge
标记。有关详细信息,请参阅。这可能是因为它在开始键入时留下了足够的空间来显示提示。这样,TextInputLayout
会将提示平滑地移动到EditText
的顶部。您可以通过使用hintEnabled=false
并删除hintI来测试这一点。恐怕这不是问题所在。在第一个屏幕截图中,提示有正确的空间量,在第二个屏幕截图中,提示增加了很多。禁用提示将删除第一个屏幕截图中的小边距,并在第二个屏幕截图中略微减少额外的空间,但不管有没有提示,仍然可能有12dp左右的额外边距。很好,我对自定义类的制作方法存在误解。它们在扩展视图类的“内部”膨胀。我真的很懒,只是扩展了一个框架布局来修复它!
<?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>