确实错误是TextView,但TextAppearance 样式只影响文本,而不影响文本所在的View。maxLines 和ellipsize 属性属于TextView,因此它们将在 TextAppearance 样式中被忽略,该样式需要 textColor、textSize、typeface 等属性。1
知道了这一点,我们只需要找到一种方法来在错误TextView 上设置这些属性的值。 kjurkovic's answer on this very question
展示了如何在代码中执行此操作,对于当前版本的 TextInputLayout。2 事实证明,我们还可以在布局 XML 中执行此操作,这可能对某些人来说更可取。
那个错误TextView是用TextInputLayout的Context实例化的,我们实际上可以在布局XML中修改它,在某种程度上,使用android:theme属性。使用具有此属性的叠加层,我们可以使 Context 的主题具有 android:textViewStyle - 本质上是 TextViews 的基本设置 - 包含我们所需的属性值。
在您的主题/样式资源 XML 中:
<style name="ThemeOverlay.TextInputLayout.TextView" parent="">
<item name="android:textViewStyle">@style/Widget.TextView.SingleLineEllipsized</item>
</style>
<style name="Widget.TextView.SingleLineEllipsized" parent="">
<item name="android:maxLines">1</item>
<item name="android:ellipsize">end</item>
</style>
在布局 XML 中的 <TextInputLayout> 上,只需添加 android:theme 属性:
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/text_input_layout_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Phone number"
android:theme="@style/ThemeOverlay.TextInputLayout.TextView">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/edit_text_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>
虽然当前的TextInputLayout 的设计细节与原来的不同,但我们可以看到maxLines 和ellipsize 设置有效:
这种方法的主要警告是TextInputLayout 的所有内部TextViews 都将具有这些基本属性值。目前,除了错误之外,还包括助手、计数器、前缀和后缀。
- 帮助器与错误位于同一位置,因此,如果您希望在其中一个上使用单线椭圆形,那么您很可能在另一个上也需要它,即使您正在使用它。
- 计数器已设置为单行,只有当计数器比
EditText 更宽时,无关的ellipsize 才会生效。
- 前缀和后缀,就其性质而言,无论如何都是单行的。
如果其中任何一个不受欢迎,那么 kjurkovic 的 findViewById() 演示应该适用于所有这些 TextViews,3 尽管您必须确保首先设置相应的文本,如 @987654357 @s 按需实例化。
1 您可以在the platform's res/values/attrs.xml resource file 中找到有效TextAppearance 属性的完整列表。我不相信有任何文档或开发人员页面涵盖它;至少,以前没有。
2TextInputLayout 的第一个版本没有将 ID 分配给内部 TextViews,因此直接引用错误 TextView 需要反射,或者笨拙地搜索内部层次结构。我没有在那些古老的版本上测试过主题覆盖解决方案,但如果由于某种原因你被困在其中并且这不起作用,previous revisions of this answer 为你提供了其他选项。
3 顺便说一下,所有这些的 ID 如下:R.id.textinput_error、R.id.textinput_helper_text、R.id.textinput_counter、R.id.textinput_prefix_text 和 R.id.textinput_suffix_text。