【问题标题】:Add entry to textview向文本视图添加条目
【发布时间】:2014-01-02 13:38:13
【问题描述】:

我认为这个问题很简单。但是作为一个初学者,我不明白该怎么做。 我已经阅读了这个教程How to make list view with multiple textviews

我的问题是:如何动态添加条目。 Adapter.add 失败。 而且我不能谷歌,因为 weather_data 是天气类型,这是未知的。 非常感谢您的帮助。

【问题讨论】:

  • 发布你的代码 n 错误日志
  • 不要直接在适配器中操作模型对象,修改活动/片段中的数据集合并调用 adapter.notifyDataSetChanged

标签: android add element custom-adapter


【解决方案1】:

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

【讨论】:

  • 非常感谢。效果很好。我会在教程的评论部分放一个链接。
【解决方案2】:

将新数据添加到您的 ArrayList 并调用函数adaptor.notifyDataSetChanged(); 这将刷新您的列表视图。并且将添加新数据。

【讨论】:

    猜你喜欢
    • 2017-05-20
    • 1970-01-01
    • 2021-07-06
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多