Подтвердить что ты не робот

Android EditText с плавающей меткой и заполнителем

Как я могу создать editText, который выглядит так?

Редактировать текст с помощью заполнителя и метки

4b9b3361

Ответ 1

Вы можете сделать это, используя TextInputLayout и EditText.

Вот ваш XML:

<android.support.design.widget.TextInputLayout
    android:id="@+id/text_input_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Label">

    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text" />

</android.support.design.widget.TextInputLayout>

1. Добавить атрибут android:hint="Label" в TextInputLayout, чтобы всегда показывать его подсказки Label.

2. Программно устанавливаем EditText подсказки Placeholder только тогда, когда EditText фокусируется.

Добавьте в свою деятельность следующие строки:

    .........
    .................

    final EditText editText = (EditText) findViewById(R.id.edit_text);

    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean hasFocus) {
            if (hasFocus) {
                editText.setHint("Placeholder");
            } else {
                editText.setHint("");
            }
        }
    });

    .........
    ..................

ВЫВОД:

введите описание изображения здесь

Надеюсь, это поможет ~

Ответ 2

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Label">

    <android.support.design.widget.TextInputEditText
        android:hint="Placeholder"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress" />

</android.support.design.widget.TextInputLayout>

Обратите внимание, что android:hint="Placeholder" из TextInputEditText отображается одновременно с android:hint="Label" из TextInputLayout, когда представление не сфокусировано. Вы можете сделать некоторую дополнительную проверку в вашем Java-коде, чтобы показать и скрыть этот ярлык. Или просто оставьте android:hint="Placeholder" от TextInputLayout.

Чтобы изменить цвет, вам нужно установить тему, используя android:theme="@style/TextLabel для TextInputLayout, и там будет установлен цветной акцент.

<style name="TextLabel" parent="TextAppearance.AppCompat.Light">
   <item name="colorAccent">@color/yourColor</item>
</style>

Ответ 3

Вы можете использовать следующий код (в kotlin). Он будет показывать местозаполнитель после задержки 200 мс (чтобы избежать совпадения намека и заполнителя).

class PlaceholderEditText : TextInputEditText {

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    private val placeholder = hint

    init {
        hint = ""
        onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                postDelayed({ hint = placeholder }, 200)
            } else {
                hint = ""
            }
        }
    }
}

а затем в макете класса xml:

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="ALWAYS VISIBLE LABEL">

        <com.myapp.widget.PlaceholderEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="DISAPPEARING PLACEHOLDER" />

    </android.support.design.widget.TextInputLayout>

Ответ 4

Вы можете использовать XML файл ниже, как показано ниже.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
    android:text="Label"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textView2"
    android:textColor="@color/wallet_holo_blue_light" />
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:text="Name"
    android:ems="10"
    android:id="@+id/editText2"
    android:hint="Placeholder" />
    </LinearLayout>

Ответ 5

Если вы используете textinputlayout, то в фокусе edittext вы не получили никакого заполнителя.

Разметка:

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/username_txt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</android.support.design.widget.TextInputLayout>

Вы должны установить прослушиватель смены фокуса edittext.

Java:

usernameTxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            usernameTxt.setHint("Label");
        } else {
            usernameTxt.setHint("Placeholder");
        }
    }
});

Ответ 6

ПОДАРОК: TextInputEditText вложенный в TextInputLayout !

TL; DR !: Используйте эту функцию расширения Kotlin

fun EditText.setHintAndLabel(
        textInputLayout: TextInputLayout,
        label: String?, // hint in the TextInputLayout
        hint: String? // hint in the EditText
) {
    this.hint = ""
    textInputLayout.hint = label

    this.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
        if (hasFocus) {
            this.hint = hint ?: ""
        } else {
            this.hint = ""
        }
    }
}

В чем проблема и как ее решить?

Проблема в том, что подсказка EditText перекрывается, если есть подсказка в TextInputLayout. Какой показать в этом случае? Хороший вопрос: мы хотим, чтобы подсказка EditText отображалась только тогда, когда она находится в TextInputLayout/курсор находится внутри, а подсказка TextInputLayout должна отображаться всегда.

⮑ Таким образом, мы устанавливаем подсказку для EditText когда он имеет фокус, и удаляем его, как только он теряет фокус. 🐙