我的RecyclerView包含看到的电影前面的复选标记。我在对RecyclerView进行排序后使用notifyDatasetChanged()
。单击菜单选项后,即使项目发生变化,复选标记也不会更改并保持在同一位置。
以下是我的活动课程的一部分:
public class SearchActivity extends AppCompatActivity {
MoviesAdapter adapter;
List<Movie> movies = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = new MovieAdapter(movies, SearchActivity.this);
recyclerView.setAdapter(adapter);
fetchMovies("ascending");
}
private void fetchMovies(String order) {
movies.clear();
movies.addAll(response.body().getMovies(order));
adapter.notifyDatasetChanged();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.ascending:
fetchMovies("ascending");
adapter.notifyDatasetChanged();
return true;
case R.id.descending:
fetchMovies("descending");
adapter.notifyDatasetChanged();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
我的MovieAdapter
:
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> {
private List<Movie> movies;
private final int rowLayout;
private final Context context;
public MovieAdapter(List<Movie> movies, Context context) {
this.movies= movies;
this.rowLayout = R.layout.movie_item;
this.context = context;
}
@Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new MovieViewHolder(view);
}
@Override
public void onBindViewHolder(final MovieViewHolder holder, @SuppressLint("RecyclerView") final int position) {...}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getItemCount() {
return movies.size();
}
public void notifyNewData(List<Movie> movies) {
this.movies= movies;
notifyDataSetChanged();
}
static class MovieViewHolder extends RecyclerView.ViewHolder {...}
}
答案 0 :(得分:0)
你应该使用movies.addAll()而不是movies.add()。因为很明显你从api响应中添加了更多的项目。
如果它不起作用,请在适配器类中创建一个方法并将新值传递给它,并从该方法中调用notifyDatasetChanged:
public void notifyNewData(List<Movie> movies){
this.movies.clear()
this.addAll(movies)
this.notifyDatasetChanged();
}
并调用adapter.notifyNewData(movies);来自你的主要班级