聚焦后更改TextInputLayout提示文本

5
在一个片段中,当用户触摸TextInputEditText时,我想更改TextInputLayout提示文本。在它向上动画成为浮动提示之前。
我可以轻松更改提示,但是我希望用户先触摸它,然后再更改。
我该怎么做?
谢谢
3个回答

3

要更改提示文本颜色,请使用View.OnFocusChangeListener来设置hintTextAppearance。尝试以下配置。

 <style name="inactive" parent="Theme.AppCompat.Light">
    <item name="android:textColorPrimary">@android:color/darker_gray</item>
    <item name="android:textColor">@android:color/darker_gray</item>
</style>

<style name="active" parent="Theme.AppCompat.Light">
    <item name="android:textColorPrimary">@android:color/black</item>
    <item name="android:textColor">@android:color/black</item>
</style>

XMl

<android.support.design.widget.TextInputLayout
    android:id="@+id/tet"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/et"
    app:hintTextAppearance="@style/inactive"
    android:layout_margin="@dimen/activity_horizontal_margin"
    app:hintEnabled="true">
    <android.support.design.widget.TextInputEditText
        android:id="@+id/edit"
        android:layout_width="match_parent"
        android:textColor="@color/colorPrimary"
        android:layout_height="wrap_content"
        android:hint="Floating Hint" />

</android.support.design.widget.TextInputLayout>

在焦点变化期间更改样式。

final TextInputLayout inputLayout=findViewById(R.id.tet);
    final TextInputEditText edit=findViewById(R.id.edit);
    edit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus)
                inputLayout.setHintTextAppearance(R.style.active);
            else
                inputLayout.setHintTextAppearance(R.style.inactive);
        }
    });

编辑:- 如果只需要更改提示文本,您可以在焦点更改时进行更改。

edit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus)
                edit.setHint("Enter name");
            else
                edit.setHint("Name");
        }
    });

1
谢谢。我的问题是我使用了TextInputLayout而不是TextInputEditText。TextInputLayout可以更改提示,但onFocusChange方法无法工作。 - Ryan
使用这个解决方案会防止键盘显示,因为设置提示将隐藏键盘。 - Stack Diego

1
您可以使用OnFocusChangedListener并检索用户具有EditText焦点的事件。
myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                     // do what you have to do
                }

            }
        });

0
尝试这个方法:

。。。

     editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            editText.setHint("Please Enter Name"); // here set new hint
        }
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接