开发者

Refresh ArrayAdapter dynamically

I have an Activity with an AutoComplete box on it. Whenever the text changes, I want to call a web service and populate the ArrayAdapter with the new String[] returned. This part all works great, except the list in the UI isn't being refreshed when there are all new values in String[] schools. The original list populated in my onCreate always remains.

I read somewhere I needed to update it on the same thread the UI is running on, so I tried the Runnable listed in my code below. But that, as well as just updating my class variable schools does not work alongside notifyOnDataSetChange()

Where am I going wrong?

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    schools = SchoolProxy.search("Co");
    autoCompleteAdapter = new ArrayAdapter(this,android.R.layout.simple_dropdown_item_1line, schools);
    autoComplete = (AutoCompleteTextView)  findViewById(R.id.edit);
    autoComplete.addTextChangedListener(textChecker);
    autoComplete.setAdapter(autoCompleteAdapter);
}
    ...
    ....
    ...

final TextWatcher textChecker = new TextWatcher() {
    public void afterTextChanged(Editable s) {}

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    public void onTextChanged(CharSequence s, int start, int before, int count) 
    {
     schools = SchoolProxy.search(s.toString());
     runOnUiThread(updateAdapter);
    }
};

private Runnable updateAdapter = new Runnable() {
  public void run() {
         autoCompleteAdapter.notifyDataSetChanged();
        }

};

As a less important side note, if开发者_开发问答 each item in schools has a name \n city,state. Is it possible to have the city & state on a second line within the auto drop down box? Just for formatting purposes. Would look cleaner if I could.

Thank you!


Have you tried the setNotifyOnChange(true)? It is supposed to properly do what you are doing manually whenever you use methods that change the list (add(T), insert(T, int), remove(T), clear()). Perhaps you have to modify the array through these methods on the ArrayAdapter?

I'm not sure if the ArrayAdapter is actually holding the reference to schools or just copied the contents while constructing the ArrayAdapter. Maybe you can take a look at the AOSP code to see what they're doing in that constructor.


After you dynamically change adapter, just need to call:

AutoCompleteTextView.showDropdown()
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜