在 AutocompleteTextView 中显示所有项目,无需编写文本

问题描述 投票:0回答:14

我有一个 AutocompleteTextView,它工作正常。当我写一个单词时,它会显示相关结果,但我想显示所有项目,而不在 AutocompleteTextView 中写任何单词。我怎样才能做到这一点。

android autocompletetextview
14个回答
92
投票

您需要扩展 AutoCompleteTextView,

“当阈值小于或等于0时,阈值为1 已申请。”。

设置阈值

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 方法)。

看这个例子


58
投票

这里有更好的解决方案

您无需自定义您的

AutoCompleteTextView
。相反,只要您需要时就拨打
autoCompleteTextView.showDropDown()
......干杯:)


33
投票

它对我有用:

向您的对象添加下一个事件方法:

    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;
        }
    });

18
投票

这对我来说非常有效,这是解决问题的简单方法:

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;
    }
});

9
投票

需要调用

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;
        }
    });

8
投票

您需要执行这些步骤才能使其完美运行

1-在你的 xml 中放入这个

    <androidx.appcompat.widget.AppCompatAutoCompleteTextView
            android:id="@+id/account_type_spinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/_16sdp"
            android:layout_marginTop="@dimen/_24sdp"
            android:layout_marginEnd="@dimen/_16sdp"
            android:background="@drawable/rounded_edt_with_border"
            android:completionThreshold="0"
            android:drawableRight="@drawable/ic_arrow_down"
            android:hint="@string/account_type"
            android:imeOptions="actionNext"
            android:inputType="text"
            android:padding="12dp"
            android:textSize="@dimen/_15sp"
             />

您只需将

android:completionThreshold
设置为零

2- 在你的java代码中放入

  mViewDataBinding.accountTypeSpinner.setOnFocusChangeListener((v, hasFocus) -> {
        if (hasFocus)
            mViewDataBinding.accountTypeSpinner.showDropDown();
    });

4
投票

用这个:

 text.setOnTouchListener(new View.OnTouchListener(){


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

2
投票
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()
}

2
投票

所有答案都已过时。通过材料设计,它变得更加容易和流畅。确保将 inputType 设置为 none,这样就不再打开键盘了。

XML

 <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/et_countries_list"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:hint="Demo hint"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"

        >

        <com.google.android.material.textfield.MaterialAutoCompleteTextView
            android:id="@+id/countries_list"
            android:layout_width="match_parent"
            android:inputType="none"
            android:layout_height="60dp"
            />

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

然后只需添加准备好适配器并添加即可。

   ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, new String[]{
                "Belgium", "France", "Italy", "Germany", "Spain", "Belgium", "France", "Italy", "Germany", "Spain"});
       
        AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView)
                findViewById(R.id.countries_list);
        autoCompleteTextView.setAdapter(adapter);

你已经完成了。它比旋转器效果更好。您还可以设置提示、错误、帮助程序。


1
投票

如果其他解决方案对您不起作用,请尝试此解决方案。点击时始终显示弹出窗口。

   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();
    }
}

0
投票

这里使用 onclicklistener 的方法,因为我发现 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;
        }
    });

我设法将其全部放入具有以下 xml 规范的 Textinputlayout 中:

<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>

0
投票

它帮助了我:

private AutoCompleteTextView autoCompleteTextViewRFID; 

...
    autoCompleteTextViewRFID = binding.choiceFieldRFID;
    List<String> rfidArray = databaseManager.readCowsRFID();
    ArrayAdapter<String> rfidAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, rfidArray);
    autoCompleteTextViewRFID.setThreshold(1);
    autoCompleteTextViewRFID.setAdapter(rfidAdapter);

...

autoCompleteTextViewTypeRange.setOnTouchListener((v, event) -> {
        autoCompleteTextViewTypeRange.showDropDown();
        return true;
    });

XML:

            <AutoCompleteTextView
            android:id="@+id/typeRange"
            android:gravity="center"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:layout_width="match_parent"
            android:layout_height="40dp" />

-1
投票

我对此有一个很好的解决方案。这很简单。这只是下拉菜单并从选项中进行选择。

确保将这两行添加到 XML 中。

android:completionThreshold="0"
android:focusableInTouchMode="false"

XML

<com.google.android.material.textfield.TextInputLayout
    android:layout_marginTop="10dp"
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.appcompat.widget.AppCompatAutoCompleteTextView
        android:id="@+id/select_area"
        android:layout_width="match_parent"
        android:layout_height="52dp"
        android:padding="10dp"
        android:textSize="15sp"
        android:singleLine="true"
        android:drawableEnd="@drawable/ic_arrow_down"
        android:completionThreshold="0"
        android:focusableInTouchMode="false"
        android:hint="Select an Area"
        android:inputType="text"
        android:maxLines="1" />

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

JAVA

area_autocomplete.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        area.showDropDown();
    }
});

-1
投票

您可以简单地使用这一行代码

autoCompleteTextView.setThreshold(100);
© www.soinside.com 2019 - 2024. All rights reserved.