【发布时间】:2017-07-19 21:02:27
【问题描述】:
【问题讨论】:
-
我没试过,但你可以考虑修改
TextInputLayout并在CollapsingTextHelper上更改the gravity that is set。 -
如果用户输入的文本仍然在左侧,非浮动提示在中间(除了浮动提示在中间)是否可以接受?
【问题讨论】:
TextInputLayout并在CollapsingTextHelper上更改the gravity that is set。
您想要的行为存在于CollapsingTextHelper 类中。不幸的是,这个类是包私有的和final,所以没有官方支持的方式让你调用你想要的方法。以下是您希望能够编写的内容:
private void setCollapsedHintMiddle(TextInputLayout layout) {
CollapsingTextHelper helper = layout.getCollapsingTextHelper();
helper.setCollapsedTextGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
}
既然你不能那样做,你可以使用反射来破解它:
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
}
}
请注意,这依赖于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>
然后在 Java 中更新TextInputEditText 的重力:
EditText emailChild = (EditText) findViewById(R.id.emailChild);
emailChild.setGravity(Gravity.START);
结果行为将是 hint 水平居中显示(视图有焦点/文本和没有焦点/文本时),而 用户输入的文本显示在左侧。
【讨论】: