我的应用中有两个ArrayLists;一个包含所有工作站的列表(AllStations
),另一个包含用户选择的工作站列表(MyStations
)。用户将从微调器中选择工作站,其中包含AllStations arraylist中的所有项目,并将添加myStations
arraylist。有一个列表视图,显示myStations
arrayList中的数据。
当用户选择要添加到mystations
arraylist的电台时,它会将其添加到“myStations”,但列表视图不会刷新。我已经尝试adapter.notifyDataSetChanged()
我花了几天谷歌搜索等,并没有找到任何理由为什么它不令人耳目一新。任何人都可以帮助我吗?
public class MyStations extends Activity{
ListView personalStations;
Spinner spinner;
ArrayList<String>AllStations = new ArrayList<String>();
ArrayList<String>MyStations = new ArrayList<String>();
ArrayAdapter<String> StationNames;
ArrayAdapter<String> myStationNames;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.my_stations);
assignStations();
spinner = (Spinner) findViewById(R.id.spinner1);
StationNames = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, AllStations);
spinner.setAdapter(StationNames);
spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
String selectedStation = spinner.getSelectedItem().toString();
MyStations.add(selectedStation);
myStationNames.notifyDataSetChanged();
TextView txt1 = (TextView) findViewById(R.id.textView1);
int size = MyStations.size();
String sizes= String.valueOf(size);
txt1.setText(sizes);
}
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
personalStations = (ListView) findViewById(R.id.myStnList);
myStationNames = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, MyStations);
personalStations.setAdapter(new ArrayAdapter<String>(MyStations.this, android.R.layout.simple_list_item_1, MyStations));
}
public void assignStations(){
ImportData stationData = new ImportData();
stationData.importStations();
AllStations = stationData.getStationNames();
}
}
答案 0 :(得分:1)
你写道:
personalStations = (ListView) findViewById(R.id.myStnList);
myStationNames = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, MyStations);
personalStations.setAdapter(new ArrayAdapter<String>(MyStations.this, android.R.layout.simple_list_item_1, MyStations));
从我看到的内容创建适配器并将其分配给myStationsNames
,但在ListView
上设置了ArrayAdapter
的新实例。在这种情况下,在notifyDataSetChanged()
上调用myStationsNames
将不会执行任何操作,因为它与小部件无关。你确定你不想写:
personalStations = (ListView) findViewById(R.id.myStnList);
myStationNames = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, MyStations);
personalStations.setAdapter(myStationsNames);