【问题标题】:ArrayAdapter not updating with notifyDataSetChanged()ArrayAdapter 未使用 notifyDataSetChanged() 进行更新
【发布时间】:2021-06-07 20:14:21
【问题描述】:

我有一个使用 ArrayList 填充的 ListView,它工作正常,但是当我用新项目清除并重新填充 ArrayList 并调用 notifyDataSetChanged() 时,永远不会调用适配器的 getView() 并且 ListView 不会反映新数据。不知道我哪里出错了,但感谢任何帮助!谢谢

初始化视图和适配器

Arraylist<Movie> moviesArray = new Arraylist<>();
movieListView = view.findViewById(R.id.movie_list_view);
movieListAdapter = new MovieListArrayAdapter(this, requireContext(), R.layout.list_item, moviesArray);
movieListView.setAdapter(movieListAdapter);

要求新数据

moviesArray.clear()
moviesViewModel.GetMovies();

观察结果(我的 BottomSheet 已更新,所以我知道我正在接收数据)

moviesViewModel.getMoviesResult().observe(getViewLifecycleOwner(), new Observer<MovieList>() {
        @Override
        public void onChanged(MovieList movieList) {
            if (movieList!=null) {
            moviesArray.addAll(movieList.getResults());
                    movieListAdapter.notifyDataSetChanged();
            }
            UpdateBottomSheet(view, 0);
        }
    });

适配器(更新列表数据时不会调用getView)

public class MovieListArrayAdapter extends ArrayAdapter<Movie> {

Fragment fragment;
List<Movie> movies;

public MovieListArrayAdapter(Fragment fragment, @NonNull Context context, int resource, @NonNull List<Movie> movies) {
    super(context, resource, movies);
    this.fragment = fragment;
    this.movies = movies;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    Movie movie = movies.get(position);
    Movie top_movie = movies.get(0);

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
    }

    ImageView movie_imageview = convertView.findViewById(R.id.list_item_image);

    if (movie==top_movie) {
        convertView.setVisibility(View.VISIBLE);
        Glide.with(fragment.requireContext()).load(movie.getImage()).into(movie_imageview);
    } else {
        convertView.setVisibility(View.GONE);
    }

    return convertView;
}

【问题讨论】:

  • movieSwipeFlickAdapter 是什么,你的意思是打电话给notifyDataSetChanged 吗?
  • 哎呀,我为帖子设置了更基本的名称,以便更容易理解,但忘了更改那个。我刚刚编辑了,抱歉。但是,是的,我在正确的适配器上调用 notifyDataSetChange()

标签: java android android-listview android-arrayadapter


【解决方案1】:

您需要更新适配器中的列表。

movieListAdapter.addAll(movieList.getResults());
movieListAdapter.notifyDataSetChanged();

【讨论】:

  • 我也尝试过,结果相同:/ 奇怪的是适配器正在获取数据,因为我在 addAll() 和 notifyDataSetChanged() 之后调用了 movieListAdapter.getItem(0).getTitle() ) 并且输出是正确的,但没有调用 getView() 来更新视图
猜你喜欢
  • 2012-04-02
  • 1970-01-01
  • 1970-01-01
  • 2013-04-19
  • 2011-06-08
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多