【发布时间】:2017-09-08 19:27:25
【问题描述】:
虽然在 stackoverflow 上有很多与此主题相关的问题,但我可以说我已经查看了其中的许多问题并尝试了不同的方法,但仍然无法正常工作。
我有一个 ListView,我用我创建的自定义类的自定义适配器填充它。我还有一个微调器,我正在尝试将其用作列表的过滤器。
这是我的简化代码,我删除了所有不相关的内容,使其尽可能清晰,还简化了一些变量名称:
public class OnlineNavActivity extends AppCompatActivity {
private ListView tourList;
private ArrayList<Tour> toursData;
private Spinner filterSpinner;
private TourAdapter tourAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tours_online);
// Set up the spinner
filterSpinner = (Spinner) findViewById(R.id.country_spinner);
addItemsToSpinner();
filterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedCountry = (String) parent.getItemAtPosition(position);
Log.i(LOG_TAG, selectedCountry);
if (!selectedCountry.equals(Data.ALL_COUNTRIES)) { // if string does not equal to "All Countries"
toursData = Data.listByFilter(selectedCountry);
}
else {
toursData = Data.dataList;
}
tourAdapter = new TourAdapter(getApplicationContext(), toursData);
tourAdapter.notifyDataSetChanged();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
toursData = Data.dataList;
tourAdapter = new TourAdapter(getApplicationContext(), toursData);
tourAdapter.notifyDataSetChanged();
}
});
// Assign all of the data to the array at first, will change by filter spinner
toursData = Data.dataList;
// Generate the list view
tourList = (ListView) findViewById(R.id.online_nav_list);
tourAdapter = new TourAdapter(this ,toursData);
tourList.setAdapter(tourAdapter);
}
(Data.listByFilter() 是我在另一个类中创建的方法,它返回一个带有应用过滤器的 ArrayList)。
问题是当我点击微调器并选择一个项目时 - 什么也没有发生。
我曾尝试使用tourAdapter.clear(),然后使用add 命令添加项目,但这不起作用(对于微调器中的任何选择,ListView 都变为空)。
将项目添加到适配器就像项目被添加到 ListView 并在那里更新一样,但这不是我需要的,只是在我试图解决这个问题时起作用的东西。
谢谢。
编辑:
在尝试了很多事情之后,我终于找到了解决方案。虽然这似乎不是一个最佳解决方案,但由于我在每个微调器操作中都声明了一个新的TourAdapter,所以这是唯一对我有用的解决方案。
我所做的是声明一个新的TourAdapter,然后调用setAdapter。
另外,我将onNothingSelected 作为一个空方法。这就是它的样子(所有其他代码保持不变):
filterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedCountry = (String) parent.getItemAtPosition(position);
Log.i(LOG_TAG, selectedCountry);
if (!selectedCountry.equals(Data.ALL_COUNTRIES)) { // if string does not equal to "All Countries"
toursData = Data.listByFilter(selectedCountry);
Log.i(LOG_TAG, "first country is" + toursData.get(0).getCountry());
}
else {
toursData = Data.dataList;
}
tourAdapter = new TourAdapter(getApplicationContext() ,toursData);
tourList.setAdapter(tourAdapter);
//tourAdapter.notifyDataSetChanged();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
【问题讨论】:
-
在我的博客中:programandroidlistview.blogspot.com,阵列适配器上的示例与您正在寻找的类似。希望有所帮助!
标签: android listview spinner adapter android-adapter