无法确定recyclerview的结尾,adapter.submitlist(list)未更新列表

ukqbszuj  于 2021-06-26  发布在  Java
关注(0)|答案(0)|浏览(242)

我试图使用onscrollistener检测recyclerview的结束,但是 OnScrollStateChanged 方法被多次调用,即使 if(!recyclerView.canScrollVertically(1)) 条件。我想应用分页,但我面临两个问题:
只能检测一次recyclerview end
一旦检索到数据,listadapter(diffutil)的 submitList(list) 方法未更新recyclerview。
onscrollstatechanged方法

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {

                if(!recyclerView.canScrollVertically(1)){
                    // search the next page
                    mArticlesViewModel.searchNextPage();
                }
            }
        });

subscribeobserver()方法

private void subscribeObservers() {
        mArticlesViewModel.getArticlesObserver().observe(getViewLifecycleOwner(), new Observer<List<NewsItem>>() {
            @Override
            public void onChanged(List<NewsItem> newsItems) {
                mArticlesViewModel.setIsPerformingQuery(false);
                progressBar.setVisibility(View.GONE);

                if (!newsItems.isEmpty()) {
                    mArticlesViewModel.setIsPerformingQuery(false);
                    initEmptyRecyclerView();
                    adapter.submitList(newsItems);

                    emptyStateTextView.setVisibility(View.INVISIBLE);
                    swipeRefreshLayout.setRefreshing(false);
                    textViewTitle.setVisibility(View.VISIBLE);
                }

                if (newsItems.isEmpty()) {
                    initEmptyRecyclerView();

                    adapter.submitList(newsItems);
                    textViewTitle.setVisibility(View.INVISIBLE);
                    emptyStateTextView.setVisibility(View.VISIBLE);
                    swipeRefreshLayout.setRefreshing(false);
                    emptyStateTextView.setText(R.string.no_news_found);
                }
            }
        });

initemptyrecylcerview()方法

public void initEmptyRecyclerView() {

        adapter = new NewsItemAdapter(mContext);
        recyclerView.setAdapter(adapter);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager
                (mContext, LinearLayoutManager.VERTICAL, false);

        recyclerView.setLayoutManager(linearLayoutManager);
    }

视图模型

public class ArticlesViewModel extends ViewModel {

    private NewsItemRepository newsItemRepository;
    private boolean mIsPerformingQuery;

    public ArticlesViewModel() {
        newsItemRepository = NewsItemRepository.getInstance();
        mIsPerformingQuery = false;
    }

    public MutableLiveData<List<NewsItem>> getArticlesObserver() {
        return newsItemRepository.getArticlesObserver();
    }

    public void getArticles(String keyword, int pageNumber) {
        mIsPerformingQuery = true;
        newsItemRepository.getArticles(keyword, pageNumber);
    }

    public void searchNextPage() {
        if (!mIsPerformingQuery) {
            newsItemRepository.searchNextPageForArticles();
        }
    }

    public void setIsPerformingQuery(Boolean isPerformingQuery) {
        mIsPerformingQuery = isPerformingQuery;
    }
}

存储库

public class NewsItemRepository {

    private static NewsItemRepository instance;
    private NewsApiClient mNewsApiClient;

    private String mQuery;
    private int mPageNumber;

    public static NewsItemRepository getInstance() {
        if (instance == null) {
            instance = new NewsItemRepository();
        }
        return instance;
    }

    public NewsItemRepository() {
        mNewsApiClient = NewsApiClient.getInstance();
    }

    public MutableLiveData<List<NewsItem>> getArticlesObserver() {
        return mNewsApiClient.getArticlesObserver();
    }

    public void getArticles(String keyword, int pageNumber) {
        if (pageNumber == 0) {
            pageNumber = 1;
        }
        mQuery = keyword;
        mPageNumber = pageNumber;
        mNewsApiClient.getArticles(keyword, pageNumber);
    }

    public void searchNextPageForArticles() {
        mNewsApiClient.getArticles(mQuery, mPageNumber + 1);
    }

    public void getNews(String keyword, int pageNumber) {
        mNewsApiClient.getNews(keyword, pageNumber);
    }
}

apiclient公司

public class NewsApiClient {

    private MutableLiveData<List<NewsItem>> articles;
    public static final String SORT_ORDER = "publishedAt";

    private static NewsApiClient instance;

    public NewsApiClient() {
        articles = new MutableLiveData<>();
    }

    public static NewsApiClient getInstance() {
        if (instance == null) {
            instance = new NewsApiClient();
        }
        return instance;
    }

    public MutableLiveData<List<NewsItem>> getArticlesObserver() {
        return articles;
    }

    public void getArticles(String keyword, int pageNumber) {

        Call<RootJsonData> rootJsonDataCall = createArticlesJsonDataCall(keyword, pageNumber);
        rootJsonDataCall.enqueue(new Callback<RootJsonData>() {
            @Override
            public void onResponse(Call<RootJsonData> call, Response<RootJsonData> response) {
                List<NewsItem> articlesList = response.body().getNewsItems();
                if (pageNumber == 1) {
                    articles.postValue(articlesList);
                } else {
                    List<NewsItem> currentNewsItemList = articles.getValue();
                    currentNewsItemList.addAll(articlesList);
                    articles.postValue(currentNewsItemList);
                }
            }

            @Override
            public void onFailure(Call<RootJsonData> call, Throwable t) {
                articles.postValue(null);
            }
        });
    }

    private Call<RootJsonData> createArticlesJsonDataCall(String keyword, int pageNumber) {
        String language = Locale.getDefault().getLanguage();
        boolean isLanguageAvailable = Utils.checkLanguage(language);
        if (isLanguageAvailable) {
            language = Utils.getLanguage();
        } else {
            language = "en";
        }

        NewsAPI newsAPI = ServiceGenerator.createService(NewsAPI.class);
        return newsAPI.searchArticlesByKeyWord(keyword, SORT_ORDER, language, Utils.API_KEY, pageNumber);
    }

适配器类

public class NewsItemAdapter extends ListAdapter<NewsItem, NewsItemAdapter.ViewHolder> {

    private Context mContext;

    private static final DiffUtil.ItemCallback<NewsItem> DIFF_CALLBACK = new DiffUtil.ItemCallback<NewsItem>() {
        @Override
        public boolean areItemsTheSame(NewsItem oldItem, NewsItem newItem) {
            return oldItem.getUrl().equals(newItem.getUrl());
        }

        @Override
        public boolean areContentsTheSame(NewsItem oldItem, NewsItem newItem) {
            return (oldItem.getTitle().equals(newItem.getTitle())
                    && oldItem.getDescription().equals(newItem.getDescription())
                    && oldItem.getAuthor().equals(newItem.getAuthor()))
                    && oldItem.getContent().equals(newItem.getContent())
                    && oldItem.getPublishedAt().equals(newItem.getPublishedAt())
                    && oldItem.getUrlToImage().equals(newItem.getUrlToImage())
                    && oldItem.getUrl().equals(newItem.getUrl())
                    && oldItem.getSource().getId().equals(newItem.getSource().getId())
                    && oldItem.getSource().getName().equals(newItem.getSource().getName());
        }
    };

    public NewsItemAdapter(Context context) {
        super(DIFF_CALLBACK);
        mContext = context;
    }

    public NewsItem getArticleAt(int position) {
        return getItem(position);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.layout_list_item, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        NewsItem newsItem = getItem(position);

        RequestOptions requestOptions = new RequestOptions();
        requestOptions.placeholder(Utils.getRandomDrawableColor());
        requestOptions.error(Utils.getRandomDrawableColor());
        requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
        requestOptions.centerCrop();

        Glide.with(mContext)
                .load(newsItem.getUrlToImage())
                .apply(requestOptions)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        holder.progressBarInImage.setVisibility(View.GONE);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        holder.progressBarInImage.setVisibility(View.GONE);
                        return false;
                    }
                })
                .transition(DrawableTransitionOptions.withCrossFade())
                .into(holder.titleImage);

        holder.textViewTitle.setText(newsItem.getTitle());
        holder.textViewDescription.setText(newsItem.getDescription());
        holder.textViewSource.setText(newsItem.getSource().getName());
        holder.textViewTime.setText(" \u2022 " + Utils.DateToTimeFormat(newsItem.getPublishedAt()));
        holder.textViewPublishedAt.setText(Utils.DateFormat(newsItem.getPublishedAt()));
        holder.textViewAuthor.setText(newsItem.getAuthor());
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private ImageView titleImage;
        private TextView textViewAuthor;
        private TextView textViewTitle;
        private TextView textViewDescription;
        private TextView textViewSource;
        private TextView textViewTime;
        private TextView textViewPublishedAt;
        private ProgressBar progressBarInImage;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            titleImage = itemView.findViewById(R.id.image_view_title);
            textViewTitle = itemView.findViewById(R.id.text_view_news_title);
            textViewAuthor = itemView.findViewById(R.id.text_view_source_author_time);
            textViewSource = itemView.findViewById(R.id.text_view_source);
            textViewTime = itemView.findViewById(R.id.text_view_time);
            textViewDescription = itemView.findViewById(R.id.text_view_news_description);
            textViewPublishedAt = itemView.findViewById(R.id.text_view_publishedAt);
            progressBarInImage = itemView.findViewById(R.id.progress_bar_image);
            itemView.setOnClickListener(this);
            itemView.setOnCreateContextMenuListener(this);
        }
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题