简体   繁体   中英

Android showDropDown onCreate not working

So I have an autocomplete view which shows a drop down when I type... But I want the dropdown to be shown when the avtivity starts. So I found this answer which says that using showDropDown() should work. And it does work in my case when called on any TouchListener or any other user triggered event. But it doesn't work if I directly just use it in onCreate()... The following code in my onCreate() works

    final AutoCompleteTextView actv = (AutoCompleteTextView)findViewById(R.id.autoCompleteUserName);
    String[] users = getResources().getStringArray(R.array.users);
    ArrayAdapter<?> adapter = new ArrayAdapter<Object>(this,R.layout.compose_ac_list_item,users);
    actv.setAdapter(adapter);

    actv.setOnTouchListener(new View.OnTouchListener(){

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // WORKS IF USED ON TOUCH
            actv.showDropDown();
              return false;
        }
    });

And the following doesn't work

    final AutoCompleteTextView actv = (AutoCompleteTextView)findViewById(R.id.autoCompleteUserName);
    String[] users = getResources().getStringArray(R.array.users);
    ArrayAdapter<?> adapter = new ArrayAdapter<Object>(this,R.layout.compose_ac_list_item,users);
    actv.setAdapter(adapter);

    actv.showDropDown();

Because when you call setAdapter it takes some time to inflate all the list items. During this time if you call showDropDown() the listview hasn't inflated yet so it won't be able to show the drop down. You could give some delay before calling the showDropDown() . But I'm not sure if this is the efficient solution as we won't be knowing for sure that how much time it is going to take to inflate the list items.

    actv.setAdapter(adapter);
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            actv.showDropDown();
        }
    }, 500);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM