在不写文本的情况下显示AutocompleteTextView中的所有项目

时间:2013-03-21 10:28:39

标签: android autocompletetextview

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

13 个答案:

答案 0 :(得分:74)

您需要扩展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);
    }
    }

}

in xml

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

编辑1

创建名为InstantAutoComplete的新类,然后将此代码放入类中。

在你的布局xml中使用这个类,如

然后在你的actity中找到这个小部件(onCreate方法)。

Look at this example

答案 1 :(得分:38)

  

更好的解决方案

您无需自定义AutoCompleteTextView。相反,只要你需要它就打电话给autoCompleteTextView.showDropDown() .....欢呼:)

答案 2 :(得分:26)

它对我有用:

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

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

答案 3 :(得分:11)

这对我很有帮助,这是解决问题的简单方法:

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

答案 4 :(得分:5)

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

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

答案 5 :(得分:4)

你需要调用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 :(得分:4)

使用它:

 text.setOnTouchListener(new View.OnTouchListener(){


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

答案 7 :(得分: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);

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

答案 8 :(得分:0)

如果其他解决方案不适合您,请尝试执行此操作。点击时会始终显示弹出窗口。

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

答案 9 :(得分:0)

这是一种使用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;
        }
    });

我设法将其全部放入具有以下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>

答案 10 :(得分:0)

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

答案 11 :(得分:0)

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

确保将这两行添加到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();
    }
});

答案 12 :(得分:0)

您只需使用这一行代码

autoCompleteTextView.setThreshold(100);