如何将 TextInputLayout 浮动提示位置更改为中间?
我已经阅读了这个答案和其他关于同一主题的答案,但它们已经超过一岁了。
我问这个问题是想看看2017年是否有任何变化。
您想要的行为存在于CollapsingTextHelper类中。不幸的是,这个类是包私有的final,所以没有官方支持的方式来调用你想要的方法。以下是您希望能够编写的内容:
private void setCollapsedHintMiddle(TextInputLayout layout) {
CollapsingTextHelper helper = layout.getCollapsingTextHelper();
helper.setCollapsedTextGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
}
Run Code Online (Sandbox Code Playgroud)
既然你不能那样做,你可以使用反射来绕过它:
private void setCollapsedHintMiddle(TextInputLayout layout) {
try {
Field helperField = TextInputLayout.class.getDeclaredField("mCollapsingTextHelper");
helperField.setAccessible(true);
Object helper = helperField.get(layout);
Method setterMethod = helper.getClass().getDeclaredMethod("setCollapsedTextGravity", int.class);
setterMethod.setAccessible(true);
setterMethod.invoke(helper, Gravity.TOP | Gravity.CENTER_HORIZONTAL);
}
catch (NoSuchFieldException e) {
// TODO
}
catch (IllegalAccessException e) {
// TODO
}
catch (NoSuchMethodException e) {
// TODO
}
catch (InvocationTargetException e) {
// TODO
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,这依赖于双方的内部实现细节TextInputLayout和CollapsingTextHelper,并随时可能破裂。
正如我在对原始问题的评论中所暗示的那样,有一种官方支持的方式可以做一些不是你想要的事情。如果你这样声明TextInputLayout:
<android.support.design.widget.TextInputLayout
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="@+id/emailChild"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:hint="Email"/>
</android.support.design.widget.TextInputLayout>
Run Code Online (Sandbox Code Playgroud)
然后在 Java 中更新TextInputEditText的重力:
EditText emailChild = (EditText) findViewById(R.id.emailChild);
emailChild.setGravity(Gravity.START);
Run Code Online (Sandbox Code Playgroud)
由此产生的行为将是提示水平居中显示(当视图有焦点/文本时和没有时),而用户输入的文本显示在左侧。