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

TextInputLayout и AutoCompleteTextView

Я использую TextInputLayout в своем приложении для Android, чтобы добиться этого аккуратного действия с плавающей меткой для моих полей ввода. Я знаю, что я должен использовать TextInputEditText, чтобы отображать подсказки в ландшафтном режиме, а вход заполняет весь экран.

Однако в некоторых моих полях ввода я получил автозаполнение, используя AutoCompleteTextView (у которого IMO имеет действительно непоследовательное имя для него - "TextView" вместо "EditText", но эта другая история), и это явно наследуется непосредственно из EditText. Таким образом, он не имеет той же функциональности, что и TextInputEditText.

Итак, мне интересно, есть ли способ достичь той же самой намеки в ландшафте (без создания моей собственной реализации TextInputAutoCompleteTextView, то есть), а также избежать предупреждений lint, которые создаются. Я что-то упустил? Полагаю, я понял, что для этой конкретной вещи они не создали пользовательские версии всех прямых и косвенных подклассов EditText, поэтому я должен был сделать свой собственный?

4b9b3361

Ответ 1

Немного поздно, но да, вам придется сворачивать свою собственную реализацию. Хорошей новостью является то, что это довольно просто. Здесь как TextInputEditText был реализован:

https://android.googlesource.com/platform/frameworks/support.git/+/master/design/src/android/support/design/widget/TextInputEditText.java

Соответственно, вот что может выглядеть TextInputAutoCompleteTextView.

public class TextInputAutoCompleteTextView extends AppCompatAutoCompleteTextView {

    public TextInputAutoCompleteTextView(Context context) {
        super(context);
    }

    public TextInputAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TextInputAutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        final InputConnection ic = super.onCreateInputConnection(outAttrs);
        if (ic != null && outAttrs.hintText == null) {
            // If we don't have a hint and our parent is a TextInputLayout, use it hint for the
            // EditorInfo. This allows us to display a hint in 'extract mode'.
            final ViewParent parent = getParent();
            if (parent instanceof TextInputLayout) {
                outAttrs.hintText = ((TextInputLayout) parent).getHint();
            }
        }
        return ic;
    }
}

Ответ 2

Совершив ответ от шахматной доски, я подумал, что подробно расскажу о том, как вы можете включить автозаполнение с подсказкой в свой проект. Вот точные шаги, которые я использовал, чтобы заставить его работать:

1) Убедитесь, что у вас есть implementation 'com.android.support:design:26.1.0' в ваших зависимостях от градиента. Точное имя пакета будет немного отличаться в зависимости от версии SDK.

2) Скопируйте класс TextInputAutoCompleteTextView из ответа @chessdork и поместите его в открытый класс внутри вашего проекта.

3) Место, где вы хотите, чтобы текст оформления автозаполнения находился в вашем XML-макете. Он должен быть структурирован следующим образом:

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="16dp">
        <mycompany.views.TextInputAutoCompleteTextView
            android:id="@+id/myAutoFill"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/myHint"/>
        </android.support.design.widget.TextInputLayout>

Ответ 3

Теперь с AndroidX вам не нужно что-то настраивать.
Нужно просто добавить стиль компонента материала (был добавлен в 1.1.0-alpha06, см. Примечания к выпуску).

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Example TextInputLayout">

    <androidx.appcompat.widget.AppCompatAutoCompleteTextView
    style="@style/Widget.MaterialComponents.AutoCompleteTextView.FilledBox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

</com.google.android.material.textfield.TextInputLayout> 

Ответ 4

Оба ответа (@chessdork и @Shn_Android_Dev) помогают достичь правильного поведения AutoCompleteTextView (ACTV) внутри TextInputLayout (TIL), однако я обнаружил, что между началом/концом TIL и ACTV внутри него не было пробела как вы можете видеть на следующем изображении:

Example of how there is no space between the ACTV and the TIL

То, что я сделал, чтобы решить проблему, заключалось в том, чтобы добавить пару добавочных значений в начало и конец TextInputAutoCompleteTextView, значения, которые работали для меня, - 12dp в начале и 8dp в конце, но, конечно, вы можете играть с этим и получите желаемый эффект. Взяв пример @Shn_Android_Dev, TextInputAutoCompleteTextView будет выглядеть так:

<mycompany.views.TextInputAutoCompleteTextView
    android:id="@+id/myAutoFill"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingStart="12dp"
    android:paddingEnd="8dp"
    android:hint="@string/myHint"/>

И теперь вид выглядит следующим образом:

Example with the correct spacing

Ответ 5

Может быть, кому-то нужен код для реализации Xamarin Android.

Вот

namespace YourNamespace
{
    public class TextInputAutoCompleteTextView : AppCompatAutoCompleteTextView
    {
        public TextInputAutoCompleteTextView(Context context) : base(context)
        {
        }

        public TextInputAutoCompleteTextView(Context context, IAttributeSet attrs) : base(context, attrs)
        {
        }

        public TextInputAutoCompleteTextView(Context context, IAttributeSet attrs, int defStyleAttr) : base(context,
            attrs, defStyleAttr)
        {
        }

        public override IInputConnection OnCreateInputConnection(EditorInfo outAttrs)
        {
            IInputConnection ic = base.OnCreateInputConnection(outAttrs);
            if (ic != null && outAttrs.HintText == null)
            {
                IViewParent parent = Parent;
                if (parent is TextInputLayout layout)
                {
                    outAttrs.HintText = new Java.Lang.String(layout.Hint);
                }
            }

            return ic;
        }
    }
}

И в XML...

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

        <YourNamespace.TextInputAutoCompleteTextView
            android:id="@+id/edtDescription"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Movements"
            android:inputType="textCapSentences" />

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

Ответ 6

С библиотекой компонентов материалов просто используйте TextInputLayout со стилем Widget.MaterialComponents.TextInputLayout.*.ExposedDropdownMenu.

Что-то вроде:

  <com.google.android.material.textfield.TextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu"
     android:hint="Hint..."
     ...>

       <AutoCompleteTextView
           android:background="@null"
           .../>

  </com.google.android.material.textfield.TextInputLayout>

enter image description here

Ответ 7

Простое решение - преобразовать ваш EditText в AutoCompleteTextView

XML

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/textInputLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"   
    <AutoCompleteTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</com.google.android.material.textfield.TextInputLayout>

Java

AutoCompleteTextView autoCompleteTextView;
TextInputLayout textInputLayout = findViewById(R.id.textInputLayout);
autoCompleteTextView = (AutoCompleteTextView) textInputLayout.getEditText();