問題描述
將 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);
一個簡單的代碼說明:布局.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:
你可以得到這樣的提示:
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() + "*");
編碼愉快!:)
這篇關于使用設計支持庫時 EditText getHint() 返回 null的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!