如何动态更新微调器?

2Re*_*eal 25 android android-spinner

我一直在尝试动态更新我的微调器在android中,但我尝试的一切都没有工作.

这是我用来更新微调器的以下代码.

typeList = dbAdapter.getList(); //array list with the values

adapter.notifyDataSetChanged();
groupSpinner.postInvalidate();
groupSpinner.setAdapter(adapter);
Run Code Online (Sandbox Code Playgroud)

typeList的值是正确的,但它们没有在Spinner中更新.

Ada*_*amC 23

实际上,您必须在适配器上调用clear/add,或者创建并设置新适配器.适配器不保留对列表的引用(它只在构造时调用列表中的Array),因此无法自行更新.

dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, newStringList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCategory.setAdapter(dataAdapter);
Run Code Online (Sandbox Code Playgroud)


Fif*_*eep 18

您不能简单地修改原始版本,List然后notifyDataSetChanged()像其他适配器一样调用,因为它不会保留原始版本List.但是,使用适配器本身可以获得相同的结果,如下所示:

spinnerAdapter.clear();
spinnerAdapter.addAll(updatedListData);
spinnerAdapter.notifyDataSetChanged(); // optional, as the dataset change should trigger this by default
Run Code Online (Sandbox Code Playgroud)

基于user392117(/sf/answers/2711711411/)的回答


Rob*_*ond 13

您只需要调用setAdapter()一次,然后调用adapter.notifyDataSetChanged()来更新数据.

  • 我发现`NotifyDataSetChanger()`可以在列表中工作,但我还没有看到它在Spinners中有效.我想有一些内部差异需要你每次都创建一个新的适配器. (13认同)

Dha*_*dra 9

当您在列表中更改数据以及何时要更新微调器时

创建适配器的新对象并将该适配器设置为微调器.它会确定的.

祝你好运.

编辑:您还需要在适配器上调用notifyDataSetChanged().


Cri*_*ian 4

是不是有错别字或者什么的?dbAdapter这就是和之间的区别adapter。如果 Spinner 已有适配器,则无需重新分配它。而且,您唯一需要做的就是更新适配器和调用notifyDataSetChanged方法。

typeList = adapter.getList(); //array list with the values
// change the values, and then
adapter.notifyDataSetChanged();
Run Code Online (Sandbox Code Playgroud)