开发者

How to disable AutoCompleteTextView's drop-down from showing up?

I use the following code to set text to an AutoCompleteTextView field. But I noticed that when I set certain text (not all text, but some) to it, it will automatically pop up the drop-down. If I do not request focus, it would be better, but just better, not entirely all right. I tried dissmissDropDwon(), it doesn't help. So, Is there any way to stop the drop-down from show开发者_StackOverflowing up after setting text and focus to it?

actv.setText("Tim Hortons");
actv.setSelection(0, actv.getText().length());
actv.requestFocus();
actv.dismissDropDown();    // doesn't help

Thank you!


Another solution is to clear the focus before setting the text:

mContactTxt.setFocusable(false);
mContactTxt.setFocusableInTouchMode(false);
mContactTxt.setText("");            
mContactTxt.setFocusable(true);
mContactTxt.setFocusableInTouchMode(true);


You can try these steps:

  1. When setting the text, also set the Threshold value to a large value so that the dropdown doesnot come.

     actv.setThreshold(1000);
    
  2. Then override the OnTouch to set the threshold back to 1.

       actv.setOnTouchListener(new OnTouchListener() {
                    @Override
        public boolean onTouch(View v, MotionEvent event) {
            actv.setThreshold(1);
            return false;
        }
    });
    


To answer my own question in case someone had the same problem:

One characteristics of AutoCompleteTextView is that if you change its text programmatically, it will drop down the selection list if the following two conditions are met: 1. It has focus; 2. The list is longer than 30-something items.

This behavior is actually, IMHO, a design flaw. When the program sets text to an AutoCompleteTextView, it would mean that the text is already correct, there is no point to popup the filtered list for user to further choose from.

actv.setText("Tim Hortons"); 
actv.setSelection(0, actv.getText().length()); 
actv.requestFocus(); 
actv.dismissDropDown();    // doesn't help 

In the above code, requestFocus() forces the ACTV to get the focus, and this causes the drop-down to pop up. I tried not to reqeuest focus, instead, I called clearFocus() after setting text. But the behavior is very .... unnatural. dissmissDropdown() doesn't help because .... I don't know, it just doesn't help. So, after much strugle, I came up with this work-around:

  1. When initializing the widget, I remembered the adapter in a class field.
  2. Change the above code to:

    mAdapter = (ArrayAdapter<String>)actv.getAdapter(); // mAdapter is a class field        
    actv.setText("Tim Hortons"); 
    actv.setSelection(0, actv.getText().length()); 
    actv.setAdapter((ArrayAdapter<String>)null); // turn off the adapter
    actv.requestFocus();
    Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        ((AutoCompleteTextView)msg.obj).setAdapter(mAdapter);
        };
    Message msg = mHandler.obtainMessage();
    msg.obj = actv;
    handler.sendMessageDelayed(msg, 200);   // turn it back on after 200ms
    

Here the trick is set the ACTV's adapter to null. Because there is no adapter, of course the system will not pop up the drop-down. But the message will reset the adapter back to the ACTV after the programmed delay of 200ms, and the ACTV will work normally as usual.

This works for me!


You can also enable/disable the drop-down like so:

// disable
actv.setDropDownHeight(0);
// enable
actv.setDropDownHeight(LayoutParams.WRAP_CONTENT);


setText("someText",false)

false means that it is not filtering


Maybe it is to late, but I've found elegant solution for this problem:

Disable filtering before setting text and enabling it after (instead of playing with focus or/and delays). You should use custom control in this case.

See example below:

public class CustomCompliteTextView extends AutoCompleteTextView {

    private boolean mIsSearchEnabled = true;

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

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

    public CustomCompliteTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void setSearchEnabled(boolean isEnabled) {
        mIsSearchEnabled = isEnabled;
    }

    @Override
    protected void performFiltering(CharSequence text, int keyCode) {
        if (mIsSearchEnabled) {
            super.performFiltering(text, keyCode);
        }
    }
}

And usage:

    text.setSearchEnabled(false);
    text.setText("Text you want to set");
    // optional, if you also want to set correct selection
    text.setSelection(text.getText().length());
    text.setSearchEnabled(true);


Funny trick. Works 100% :)

tv.setThreshold(Integer.MAX_VALUE);
tv.setText(station.getName());
tv.setThreshold(1);


act.post(new Runnable() 
{
  @Override
  public void run()
  {
    act.dismissDropDown();
  }
});

Works just fine!


wwyt, I simply reused your trick with removing the Adapter and these are the bare essentials to unfocus/dismiss the dropdown.

AutoCompleteTextView tvSuburbs;
ArrayAdapter<Suburb> a = (ArrayAdapter<Suburb>) tvSuburbs.getAdapter();
tvSuburbs.setAdapter(null); // Remove the adapter so we don't get a dropdown
tvSuburbs.setText(s.name); // when text is set programmatically.
tvSuburbs.setAdapter(a); // Restore adapter


You can try

searchInput.setAdapter((ArrayAdapter<String>) null);
searchInput.setText(text);
searchInput.setAdapter(adapter);

Source


Try it in XML...

<TextView  
android:layout_width="fill_parent" 
android:layout_height="wrap_content"
android:autoText="false"
/>


I too faced a scenario and I resolved in this way.

  1. Store the values that you want to show, in a static way (Ex.POJO).
  2. Check whether the stored static variable is not null and not empty.
  3. if, its not empty / not null / its length greater than 0, set dismissDropDown() for that autocompleteTextView.

Please find the below snippet

if(null != testText && testText.length() != 0) {
    mAutoCompleteSearch.setText(incomingActivity.toString());
    mAutoCompleteSearch.dismissDropDown(); //Dismiss the drop down
    } else {
    mAutoCompleteSearchDocketActivity.setText("");
            // Here it(drop down) will be shown automatically
    }

Hope, this would help for someone, Cheers !


I suppose you are using this kind of structure

<TextInputLayout>
    <AutoCompleteTextView/>
</TextInputLayout>

To disable dropdown menu, you need to set isEnabled field to false only in TextInputLayout


dismissDropDown() works well in an adapter:

        SimpleCursorAdapter autoCompleteAdapter = new SimpleCursorAdapter(this,
                    android.R.layout.select_dialog_item, null,
                    new String[] { ContactsContract.Contacts.DISPLAY_NAME },
                    new int[] { android.R.id.text1 }, 0);
        mSearchView.setAdapter(autoCompleteAdapter); 
        autoCompleteAdapter.setFilterQueryProvider(new FilterQueryProvider() {
            @Override
            public Cursor runQuery(CharSequence constraint) {
               mSearchView.dismissDropDown();
               // return your query code
            }
        });

Hope it will be helpful.


I have solved the same problem with this code:

contacts_search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                contacts_search.dismissDropDown();      
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub
                contacts_search.dismissDropDown();
            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                contacts_search.dismissDropDown();
            }
        });

Here, contacts_search is my AutoCompleteTextView


I need to add some delay to make this thing work.

This worked for me:

new Handler().postDelayed(new Runnable() {
    public void run() {
        if(carModel.isPopupShowing())
            carModel.dismissDropDown();
}}, 500);


The intent here is to hide the drop-down with AutoCompleteTextView. Set the dropDownHeight to zero in the layout file.

<!--Skipping all other attributes for simplicity-->
<AutoCompleteTextView
        android:id="@+id/address_bar"
        android:dropDownHeight="0dp"
        />

In my case, I have the GridView and there is address bar above that view. I want to filter items in GridView based upon user input in AutoCompleteTextView without requiring TextView to show me the dropdown.


Disabling just the height leaves an ugly drop shadow. Also set the width to 0.

// disable
actv.setDropDownHeight(0);
actv.setDropDownWidth(0);
// enable
actv.setDropDownHeight(LayoutParams.WRAP_CONTENT);
actv.setDropDownWidth(LayoutParams.MATCH_PARENT);


In AppCompatAutoCompleteTextView can not setTreshold(). If use AppCompatAutoCompleteTextView class, can try this:

actv.setText("Tim Hortons");
actv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            actv.setText("");
        }
    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜