实现这一目标可能有三种方法:
1将TextInputLayout上的android:hint设置为空格_字符,并在EditText上设置android:hint="This is my cool hint" 。
< <
这是有效的,因为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而不是设计支持库中的CTextInoutLayout :
< <
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.");