我写下以下申请:
我使用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 :(得分:11)
请勿修改ArrayList
。使用ArrayAdapter
,add()
和insert()
修改remove()
。您无需担心notifyDataSetChanged()
。
此外,我同意Mayra - 考虑使用AsyncTask
代替您的主题和runOnUiThread()
组合。
答案 1 :(得分:2)
在函数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);
似乎它不是一个完美的,但它有效!