Отключить/удалить текст подсказки с плавающей меткой в TextInputLayout XML
Это может показаться противоречивым, но есть ли способ отключить или удалить подсказку с плавающей меткой в TextInputLayout
? Причина, по которой я хочу использовать TextInputLayout
, а не только EditText
, - это счетчик, который предоставляет TextInputLayout
.
Вот что я до сих пор:
<android.support.design.widget.TextInputLayout
android:id="@+id/textContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
app:counterEnabled="true"
app:counterMaxLength="100">
<EditText
android:id="@+id/myEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top|left"
android:inputType="textMultiLine|textCapSentences"
android:maxLength="100"
android:scrollbars="vertical"
android:hint="This is my cool hint"/>
</android.support.design.widget.TextInputLayout>
Ответы
Ответ 1
Начиная с версии 23.2.0 библиотеки поддержки вы можете позвонить
setHintEnabled(false)
или помещая его в свой XML-текст TextInputLayout как таковой:
app:hintEnabled="false"
Хотя имя может заставить вас думать, что оно удаляет все подсказки, оно просто удаляет плавающий.
Связанные документы и проблемы: http://developer.android.com/reference/android/support/design/widget/TextInputLayout.html#setHintEnabled(boolean)
https://code.google.com/p/android/issues/detail?id=181590
Ответ 2
Возможно, есть три способа достичь этого:
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 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.");
Ответ 3
С com.google.android.material вы можете скрыть с помощью
<com.google.android.material.textfield.TextInputLayout
....
app:hintAnimationEnabled="false"
app:hintEnabled="false"
>
<com.google.android.material.textfield.TextInputEditText
........
android:hint="@string/label_hint"
/>
</com.google.android.material.textfield.TextInputLayout>
Ответ 4
Я перепробовал все ответы, но ни один из них не работает (специально для com.google.android.material: material: 1.1.0-beta01). Даже если мы внесем изменения в логику добавления EditText в TextInputLayout, у нас будет пустое пространство над полем, закрывающее половину текста и подсказку. Теперь у меня есть решение проблемы. Главное - это заполнение в EditText, как упомянуло в material.io:
<com.google.android.material.textfield.TextInputLayout
. . .
android:layout_height="wrap_content"
app:hintEnabled="false"
app:startIconDrawable="@drawable/ic_search_black"
app:endIconMode="clear_text">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/et_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="12dp"
android:hint="@string/showcase_search_hint_text"
android:inputType="text" />
</com.google.android.material.textfield.TextInputLayout>
Это позволяет нам реализовать представление 'SearchView' -like со значком поиска и кнопкой удаления текста без какой-либо уродливой "магии" с настраиваемыми представлениями.
Ответ 5
Я думаю, это поможет вам:
textContainer.setHintAnimationEnabled(false);
Ответ 6
обновите библиотеку дизайна до v23 и добавьте app:hintAnimationEnabled="false"
в TextInputLayout