notifyDataSetChanged不起作用?

问题描述:

我写以下应用:notifyDataSetChanged不起作用?

  • 存在AutoCompleteTextView字段
  • 作为适配器我使用ArrayAdapter与ListArray
  • 的ListArray由一些字符串常量项和一个项目,这将被动态地改变的每次用户输入字段中的东西

我带了TextChangedListener来更新这最后一个列表项。但看起来,更新只发生一次。

我添加了一些我的代码。可能有人会告诉我,我做错了什么。

public class HelloListView extends Activity 
{ 
    List<String> countryList = null;  
    AutoCompleteTextView textView = null; 
    ArrayAdapter adapter = null; 

    static String[] COUNTRIES = new String[] 
    { 
      "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", 
      "Yemen", "Yugoslavia", "Zambia", "Zimbabwe", "" 
    }; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main);   

     countryList = Arrays.asList(COUNTRIES); 

     textView = (AutoCompleteTextView) findViewById(R.id.edit); 
     adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, countryList); 
     adapter.notifyDataSetChanged();   
     textView.setAdapter(adapter); 
     textView.setThreshold(1); 

     textView.addTextChangedListener(new TextWatcher() 
     { 

      public void onTextChanged(CharSequence s, int start, int before, int count) 
      {    
       countryList.set(countryList.size()-1, "User input:" + textView.getText());     
      } 

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

      public void afterTextChanged(Editable s) 
      { 
      } 
     }); 

     new Thread() 
     { 
      public void run() 
      { 
       // Do a bunch of slow network stuff. 
       update(); 
      } 
     }.start();   
    } 

    private void update() 
    { 
     runOnUiThread(new Runnable() 
     { 
      public void run() 
      { 
       adapter.notifyDataSetChanged(); 
      } 
     }); 
    } 
} 
+0

不知道你为什么不起作用,但你有没有考虑使用AsyncTask做你的网络东西?它给你一个简单的方法来在另一个线程上工作,然后在UI线程上做一些工作。 http://developer.android.com/reference/android/os/AsyncTask.html – 2010-09-08 17:48:36

+0

但是,如果你看看我的例子,根本没有网络的东西。我有ArrayList的数据已经在代码中。 – Tima 2010-09-09 06:48:16

+0

尝试了您的建议。它不起作用 – Tima 2010-09-11 09:46:16

请勿修改ArrayList。修改ArrayAdapter,使用add(),insert()remove()。您无需担心notifyDataSetChanged()

另外,我同意梅拉 - 考虑用AsyncTask代替你的线程和runOnUiThread()的组合。

+0

我有一个建议,使用stackoverflow runOnUIThread。添加,插入和删除操作在我的情况下不是很好。我想只有一个项目,我会改变。 – Tima 2010-09-08 18:50:55

在功能onTextChanged(),创建一个新的适配器和连接它,然后它会工作:

countryList.set(countryList.size()-1, "User input:" + textView.getText());  
adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, countryList); 
textView.setAdapter(adapter); 

看来,这是不是一个完美的人,但它的工程!

+0

感谢您的帮助! – DigaoParceiro 2017-06-11 23:34:15