我认为问题很简单。但作为初学者,我不明白该怎么做。 我已阅读本教程How to make list view with multiple textviews
我的问题是:如何动态添加条目。 Adapter.add失败。 我不能谷歌因为weather_data是天气类型,这是未知的。 非常感谢您的帮助。
答案 0 :(得分:0)
本教程使用的java数组在创建后很难添加:
Weather weather_data[]
使用的自定义适配器不会覆盖Add方法,这也就是它无法正常工作的原因。我建议使用ArrayList来保存类型为Weather的对象。在MainActivity中:
ArrayList<Weather> weather_data = new ArrayList<Weather>();
weather_data.add(new Weather(R.drawable.weather_cloudy, "Cloudy"));
weather_data.add(new Weather(R.drawable.weather_showers, "Showers"));
weather_data.add(new Weather(R.drawable.weather_snow, "Snow"));
weather_data.add(new Weather(R.drawable.weather_storm, "Storm"));
weather_data.add(new Weather(R.drawable.weather_sunny, "Sunny"));
在WeatherAdapter中:
将类变量'data'的类型从数组更改为ArrayList:
Weather data[] = null;
成为:
ArrayList<Weather> data = null;
更改构造函数以接受ArrayList而不是数组:
public WeatherAdapter(Context context, int layoutResourceId, ArrayList<Weather> data)
在getView方法中,您需要更改获取正确数组元素的语法(使用ArrayList get方法):
Weather weather = data.get(position);
然后,您可以从MainActivity动态添加项目。例如:
weather_data.add(new Weather(R.drawable.weather_stormy, "Stormy"));
adapter.notifyDataSetChanged();
答案 1 :(得分:-2)
将新数据添加到ArrayList并调用函数adaptor.notifyDataSetChanged();
这将刷新您的列表视图。并且将添加新数据。