所以我遇到了一个奇怪的问题,但我不太知道为什么会发生。
我有 2 个微调器,每个微调器的数据几乎相同。
以下是我创建适配器的方法:
ArrayList<String> resourceSoldOptions = new ArrayList<String>();
resourceSoldOptions.addAll(Arrays.asList(getResources().getStringArray(R.array.trade_calc_resource_names)));
ArrayList<String> resourceBoughtOptions = resourceSoldOptions;
final ArrayAdapter<String> resourceSoldAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, resourceSoldOptions);
final ArrayAdapter<String> resourceBoughtAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, resourceBoughtOptions);
并设置旋转器的数据:
resourceSoldSpinner.setAdapter(resourceSoldAdapter);
resourceBoughtSpinner.setAdapter(resourceBoughtAdapter);
然后,我有一个监听器 (onItemSelectedListener
),它将根据已售旋转器的选择更改已购买旋转器的选项
这是我的做法:
resourceSoldSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Get the resource chosen
String resourceChosen = (String) parent.getItemAtPosition(position);
//And remove the option from the bought options
resourceBoughtAdapter.remove(resourceChosen);
resourceBoughtAdapter.notifyDataSetChanged();
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
但由于某种原因,已售出的旋转器受到了影响,甚至没有代码建议应该更改它。
我的处理方式是错误的吗?这看起来很可能是,所看到的选项需要根据选择不断添加/删除。
最佳答案
问题是 resourceBoughtOptions
和 resourceSoldOptions
使用相同的 ArrayList 对象。
当您创建购买列表时,您可以这样做:
ArrayList<String> resourceBoughtOptions = resourceSoldOptions;
您永远不会将 resourceBoughtOptions
初始化为新的 ArrayList 实例 - 您声明它与 resourceSoldOptions
是相同的列表。因此,您实际上只是为同一个列表指定了两个名称。
最简单的解决方法是这样做:
ArrayList<String> resourceBoughtOptions = new ArrayList<String>();
resourecBoughtOptions.addAll(resourceSoldOptions);
这实际上会为 resourceBoughtOptions
创建一个新列表,并复制 resourceSoldOptions
中的所有项目。
关于java - Android 从一个适配器中删除选项会改变另一个适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25206028/