可能有三种方法可以实现这一目标:
1设置android:hint
为TextInputLayout
空格_
字符,并保持android:hint="This is my cool hint"
设置在EditText
.
<android.support.design.widget.TextInputLayout
....
....
android:hint=" "> <<----------
<EditText
....
....
android:hint="This is my cool hint"/> <<----------
</android.support.design.widget.TextInputLayout>
这是有效的,因为在使用提示TextInputLayout
之前执行以下检查:EditText's
// If we do not have a valid hint, try and retrieve it from the EditText
if (TextUtils.isEmpty(mHint)) {
setHint(mEditText.getHint());
// Clear the EditText's hint as we will display it ourselves
mEditText.setHint(null);
}
通过设置android:hint=" "
,if (TextUtils.isEmpty(mHint))
评估为false
,并且EditText
保留其提示。
2第二种选择是子类化TextInputLayout
并覆盖其addView(View child, int index, ViewGroup.LayoutParams params)
方法:
public class CTextInputLayout extends TextInputLayout {
public CTextInputLayout(Context context) {
this(context, null);
}
public CTextInputLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CTextInputLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (child instanceof EditText) {
// cache the actual hint
CharSequence hint = ((EditText)child).getHint();
// remove the hint for now - we don't want TextInputLayout to see it
((EditText)child).setHint(null);
// let `TextInputLayout` do its thing
super.addView(child, index, params);
// finally, set the hint back
((EditText)child).setHint(hint);
} else {
// Carry on adding the View...
super.addView(child, index, params);
}
}
}
然后使用您的自定义CTextInoutLayout
而不是设计支持库中的自定义:
<your.package.name.CTextInputLayout
....
.... > <<----------
<EditText
....
....
android:hint="This is my cool hint"/> <<----------
</your.package.name.CTextInputLayout>
3第三,也可能是最直接的方法是进行以下调用:
// remove hint from `TextInputLayout`
((TextInputLayout)findViewById(R.id.textContainer)).setHint(null);
// set the hint back on the `EditText`
// The passed `String` could also be a string resource
((EditText)findViewById(R.id.myEditText)).setHint("This is my cool hinttt.");