使用设计支持库时,EditText getHint()返回null [英] EditText getHint() returns null when using design support library
问题描述
当将EditText与Design lib的(版本22.2.1)结合使用时,以编程方式获取提示的TextInputLayout将返回null.
When using EditText in combination with Design lib's (ver 22.2.1) TextInputLayout getting hint programmatically returns null.
我正在尝试以编程方式将星号'*'附加到必填字段,因此EditText.getHint()
,但是在这种情况下,它返回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);
一个简单的代码说明: Layout.xml:
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");
依赖性:编译'com.android.support:design:22.2.1'
dependency: compile 'com.android.support:design:22.2.1'
先前相关的问题这里!
推荐答案
实际上,提示移到包围EditText
视图的父视图TextInputLayout
:
Actually the hint moves to the parent view TextInputLayout
that surrounds the EditText
view:
您可以得到如下提示:
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() + "*");
祝您生日快乐! :)
这篇关于使用设计支持库时,EditText getHint()返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!