Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

android - EditText getHint() returns null when using design support library

When using EditText in combination with Design lib's (ver 22.2.1) TextInputLayout getting hint programmatically returns null.

I'm trying to append asterisk '*' to a mandatory field programmatically, hence EditText.getHint() but the fact that it returns null is an issue in this case.

EditText editText = (EditText) findViewById(R.id.edit2);
String hint = String.format("%s *", editText.getHint());
editText.setHint(hint);

Asterisk overlays the hint

A simple code illustration: Layout.xml:

<android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <EditText
            android:id="@+id/edit2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hello_world"
            android:inputType="text"/>
</android.support.design.widget.TextInputLayout>

Java:

EditText editText = (EditText) findViewById(R.id.edit2);
if (editText.getHint() == null) throw new AssertionError("Hint should not be null");

dependency: compile 'com.android.support:design:22.2.1'

Previously related issue here!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Actually the hint moves to the parent view TextInputLayout that surrounds the EditText view:

You can get the hint like this:

android.support.design.widget.TextInputLayout parent = (android.support.design.widget.TextInputLayout) yourEditText.getParent();
String hint = parent.getHint().toString();

And if you want to add * make it like this:

parent.setHint(parent.getHint() + "*");

Happy codding! :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...