【问题标题】:Change TextInputLayout floating hint position to middle?将 TextInputLayout 浮动提示位置更改为中间?
【发布时间】:2017-07-19 21:02:27
【问题描述】:

如何将 TextInputLayout 浮动提示位置更改为中间?

我有 read 这个答案和其他关于同一主题的答案,但他们已经一岁多了。

我问这个问题,看看2017年有没有变化。

【问题讨论】:

标签: android xml


【解决方案1】:

您想要的行为存在于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
    }
}

请注意,这依赖于TextInputLayoutCollapsingTextHelper 的内部实现细节,并且可能随时中断。

编辑

正如我在对原始问题的评论中提到的那样,有一种官方支持的方法可以做一些你不想要的事情。如果您像这样声明您的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 水平居中显示(视图有焦点/文本和没有焦点/文本时),而 用户输入的文本显示在左侧。

【讨论】:

    猜你喜欢
    • 2015-11-19
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多