Show all items in AutocompleteTextView without writing text

二次信任 提交于 2020-06-09 10:57:24

问题


I have a AutocompleteTextView and it works fine. When I write a word it shows the relevant result but I want to show all items without writing any word in AutocompleteTextView. How can I do that.


回答1:


You need to extend AutoCompleteTextView,

"When threshold is less than or equals 0, a threshold of 1 is applied.".

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

EDIT 1

Create new class named InstantAutoComplete then put this code into the class.

In your layout xml use this class like

then find this widget in your actity (onCreate method).

Look at this example




回答2:


BETTER SOLUTION HERE

You don't need to customize your AutoCompleteTextView. Instead just call autoCompleteTextView.showDropDown() Whenever you need it.....cheers :)




回答3:


It Works for me:

add to your object next event methods:

    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:


This works for me perfectly, this is an easy way to resolve the problem:

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:


You need to call requestFocus(); to show keyboard, otherwise keyboard does not pop up.

The method forcefully shows drop-down list.

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:


use this :

 text.setOnTouchListener(new View.OnTouchListener(){


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



回答7:


you need to put those steps to make it work perfectly

1-in your xml put this

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

you just need to set android:completionThreshold to zero

2- in your java code put

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



回答8:


Nothing Custom Required.

I tried All solutions but in some case that does not work. For Example one solution work for first time but when you remove text it will not appear. So I dug more and found following solution.

Suggestions are welcome.

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>

Kotlin:

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



回答9:


If other solutions does not work for you try this instead. Popup is displayed always on click.

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



回答10:


Here an approach with onclicklistener as I found tat onTouch was a bit irritating when trying to scroll. mOccupation is the AutocompleteTextView in question.

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

I managed to put it all into a Textinputlayout with the following xml specifications:

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



回答11:


I got a great solution to this. It's simple. This is just the drop-down and choosing from the options.

Make sure you add these two lines to 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();
    }
});


来源:https://stackoverflow.com/questions/15544943/show-all-items-in-autocompletetextview-without-writing-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!