gpt4 book ai didi

android - notifyDataSetChanged 不起作用?

转载 作者:太空狗 更新时间:2023-10-29 15:35:31 25 4
gpt4 key购买 nike

我写了下面的应用程序:

  • 有一个 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();
}
});
}
}

最佳答案

不要修改ArrayList。使用 add()insert()remove() 修改 ArrayAdapter。您无需担心 notifyDataSetChanged()

此外,我同意 Mayra 的观点——考虑使用 AsyncTask 而不是您的线程和 runOnUiThread() 组合。

关于android - notifyDataSetChanged 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3670500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com