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

Показать все элементы в AutocompleteTextView без ввода текста

У меня есть AutocompleteTextView, и он отлично работает. Когда я пишу слово, он показывает соответствующий результат, но я хочу показать все элементы без написания каких-либо слов в AutocompleteTextView. Как мне это сделать.

4b9b3361

Ответ 1

Вам нужно расширить AutoCompleteTextView,

"Когда порог меньше или равен 0, применяется порог 1".

setThreshold

import android.content.Context;  
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.AutoCompleteTextView;

public class InstantAutoComplete extends AutoCompleteTextView {

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

    public InstantAutoComplete(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);
    }

    public InstantAutoComplete(Context arg0, AttributeSet arg1, int arg2) {
        super(arg0, arg1, arg2);
    }

    @Override
    public boolean enoughToFilter() {
        return true;
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction,
            Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
       if (focused && getFilter()!=null) {
        performFiltering(getText(), 0);
    }
    }

}

в XML

<AutoCompleteTextView ... /> to <your.namespace.InstantAutoComplete ... />

РЕДАКТИРОВАТЬ 1

Создайте новый класс с именем InstantAutoComplete и поместите этот код в класс.

В вашем макете XML используйте этот класс, как

затем найдите этот виджет в вашей деятельности (метод onCreate).

Посмотрите на этот пример

Ответ 2

ЛУЧШЕ РЕШЕНИЕ ЗДЕСЬ

Вам не нужно настраивать AutoCompleteTextView. Вместо этого просто позвоните autoCompleteTextView.showDropDown() Всякий раз, когда вам это нужно..... приветствия:)

Ответ 3

Это работает для меня:

добавить к вашему объекту следующие методы событий:

    myView.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus)
                myView.showDropDown();

        }
    });

    myView.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            myView.showDropDown();
            return false;
        }
    });

Ответ 4

Это отлично работает для меня, это простой способ решить проблему:

final ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line, usernameLists);
etUsername.setThreshold(1);
etUsername.setAdapter(adapter);
etUsername.setOnTouchListener(new View.OnTouchListener() {

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
        if (usernameLists.size() > 0) {
                // show all suggestions
                if (!etUsername.getText().toString().equals(""))
                    adapter.getFilter().filter(null);
                etUsername.showDropDown();
            }
        return false;
    }
});

Ответ 5

вам нужно вызвать requestFocus(); для отображения клавиатуры, иначе клавиатура не появится.

метод принудительно отображает выпадающий список.

autocomptv.setOnTouchListener(new OnTouchListener() {

        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
            // TODO Auto-generated method stub
            autocomptv.showDropDown();
            autocomptv.requestFocus();
            return false;
        }
    });

Ответ 6

используйте это:

 text.setOnTouchListener(new View.OnTouchListener(){


            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                // TODO Auto-generated method stub
                text.showDropDown();
                return false;
            }
            });

Ответ 7

Если другие решения не работают, попробуйте это. Всплывающее окно отображается всегда при нажатии.

   public class InstantAutoComplete extends AppCompatAutoCompleteTextView {

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

    public InstantAutoComplete(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);
    }

    public InstantAutoComplete(Context arg0, AttributeSet arg1, int arg2) {
        super(arg0, arg1, arg2);
    }

    @Override
    public boolean enoughToFilter() {
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            performClick();
        }
        return super.onTouchEvent(event);
    }

    @Override
    public boolean performClick() {
        if (getFilter() != null && !isPopupShowing()) {
            performFiltering(getText(), 0);
            showDropDown();
        }
        return super.performClick();
    }
}

Ответ 8

Здесь подход с onclicklistener, как я обнаружил, что tat onTouch немного раздражает при попытке прокрутки. mOccupation - это рассматриваемый AutocompleteTextView.

    mOccupation=(AutoCompleteTextView) findViewById(R.id.actv_occupation);
    ArrayAdapter<String> occupationAdapter=new ArrayAdapter<String> 
    (NewClientActivity.this,
            android.R.layout.simple_list_item_1,
            getResources().getStringArray(R.array.occupation_array));
    mOccupation.setAdapter(occupationAdapter);
    mOccupation.setKeyListener(null);
    mOccupation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //mOccupation.setText(null);
            ((AutoCompleteTextView) view).showDropDown();
            return;
        }
    });

Мне удалось поместить все это в Textinputlayout со следующими спецификациями xml:

<android.support.design.widget.TextInputLayout
    android:id="@+id/lo_occupation"
    android:layout_marginTop="10dp"
    android:layout_gravity="center_horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <AutoCompleteTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="occupation"
        android:focusableInTouchMode="false"<--this is the important part
        android:id="@+id/actv_occupation"
        android:ems="10"
        android:completionThreshold="0"<--this too
        />
</android.support.design.widget.TextInputLayout>

Ответ 9

Nothing Custom Required.

Я перепробовал все решения, но в некоторых случаях это не работает. Например, первое решение работает впервые, но при удалении текста оно не появится. Поэтому я выкопал больше и нашел следующее решение.

Предложения приветствуются.

XML:

<android.support.design.widget.TextInputLayout
                    android:id="@+id/tl"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">

                    <android.support.v7.widget.AppCompatAutoCompleteTextView
                        android:id="@+id/autoComplete"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="Hint Here" />


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

Котлин:

val adapter = ArrayAdapter<BusinessNoResult>(context, android.R.layout.select_dialog_item, listItems)
autoComplete.setAdapter(adapter)
//threshold specifies the minimum number of characters the user has to type in 
//the
//edit box before the drop down list is shown
autoComplete.threshold = 0

//we have to add check for 0 number of character in edit text. When that 
//happens, we will show pop up manually
autoComplete.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(s: Editable?) {}

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        //first check if length of input is 0
        if(s?.length ?: 0 == 0){
            //if you don't use handler with post delay, the API will hide pop 
            //up, even if you show it. There could be better ways to this, but 
            //I have implemented this and after 100 millis it gives an animated 
            //look
            Handler().postDelayed({
                //manually show drop down
                autoComplete.showDropDown()
            }, 100) // with 100 millis of delay
        }
    }
})
//when user focus out the view, drop down vanishes. When come back it will not 
//show, so to cover this scenario add following.
autoComplete.setOnFocusChangeListener { _, hasFocus ->
    //when gain focus manually show drop down
    if(hasFocus)
        autoComplete.showDropDown()
}