本教程使用了一个创建后很难添加的 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();