显示在导航抽屉片段中的空白屏幕的recyclerview项目

时间:2019-06-04 10:13:42

标签: java android android-recyclerview retrofit navigation-drawer

我正在开发新闻,并且已经在导航抽屉片段中实现了带有搜索视图的recyclerview,但是导航抽屉中的recyclerview项目显示空白屏幕。  在片段类中,我的根URL下方有两个终点。

private static final String ROOT_URL = "https://newsapi.org";

在我的头条新闻下方,我成为头条新闻。

 @GET("/v2/top-headlines?sources=bbc-sport&apiKey=my-api-key")
    Call<SportNews> getArticles();

在我得到所有东西的第二个终点以下

 @GET("/v2/everything?apiKey=my-api-key")
    Call<Search> getSearchViewArticles(@Query("q") String q);

在BBCSportsFragment类下,我已经实现了RecyclerView和SearchView

public class BBCSportFragment extends Fragment implements ArticleAdapter.ClickListener {

public static List<Article> articleList = new ArrayList<>();

public static List<Article> origArticleList = new ArrayList<>();

@ActivityContext
public Context activityContext;
Search search;
@ApplicationContext
public Context mContext;

@BindView(R.id.recycler_view)
RecyclerView recyclerView;
BBCSportFragmentComponent bbcSportFragmentComponent;
BBCFragmentContextModule bbcFragmentContextModule;
private SportNews sportNews;
private static ArticleAdapter articleAdapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_bbcsport, container, false);
    ButterKnife.bind(this, view);
    SportInterface sportInterface = SportClient.getApiService();
    Call<SportNews> call = sportInterface.getArticles();
    call.enqueue(new Callback<SportNews>() {
        @Override
        public void onResponse(Call<SportNews> call, Response<SportNews> response) {
            if (response == null) {
                sportNews = response.body();
                if (sportNews != null && sportNews.getArticles() != null) {
                    articleList.addAll(sportNews.getArticles());

                }
                articleAdapter = new ArticleAdapter(articleList, sportNews);
                ApplicationComponent applicationComponent;
                applicationComponent = (ApplicationComponent) MyApplication.get(Objects.requireNonNull(getActivity())).getApplicationContext();
                bbcSportFragmentComponent = (BBCSportFragmentComponent) DaggerApplicationComponent.builder().contextModule(new ContextModule(getContext())).build();
                bbcSportFragmentComponent.injectBBCSportFragment(BBCSportFragment.this);
                RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(applicationComponent));
                recyclerView.setLayoutManager(layoutManager);
                recyclerView.setAdapter(articleAdapter);
            }
        }

        @Override
        public void onFailure(Call<SportNews> call, Throwable t) {

        }
    });


    SportInterface searchInterface = SportClient.getApiService();
    Call<Search> searchCall = searchInterface.getSearchViewArticles("q");
    searchCall.enqueue(new Callback<Search>() {
        @Override
        public void onResponse(Call<Search> call, Response<Search> response) {
            search = response.body();

            if (search != null && search.getArticles() != null) {
                articleList.addAll(search.getArticles());
                origArticleList.clear();
                origArticleList.addAll(search.getArticles());
            }

            articleAdapter = new ArticleAdapter(articleList, search);
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setAdapter(articleAdapter);
        }

        @Override
        public void onFailure(Call<Search> call, Throwable t) {

        }
    });


    return view;


}

private Context getContext(ApplicationComponent applicationComponent) {
    return null;
}

public static void doFilter(String searchQuery) {
    searchQuery = searchQuery.toLowerCase();
    articleList.clear();
    for (Article article : origArticleList) {
        final String text = article.getTitle();
        if (text.equals(searchQuery))
            articleList.add(article);
    }
    articleAdapter.notifyDataSetChanged();
}
}

在适配器类之下

public class ArticleAdapter extends RecyclerView.Adapter<ArticleAdapter.CustomViewHolder> {

public static final String urlKey = "urlKey";
List<Article> articles;

private ClipboardManager myClipboard;
private ClipData myClip;


public ArticleAdapter(List<Article> articles, SportNews sportNews) {
    this.articles = articles;


}

public ArticleAdapter(ClickListener clickListener) {
}

public ArticleAdapter(List<Article> articleList, Search search) {
}

@NonNull
@Override
public ArticleAdapter.CustomViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.article_list, null);
    return new ArticleAdapter.CustomViewHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull edgar.yodgorbek.sportnews.adapter.ArticleAdapter.CustomViewHolder customViewHolder, int position) {
    Article article = articles.get(position);
    SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy");

    Date d = new Date();
    try {
        d = input.parse(article.getPublishedAt());
    } catch (ParseException e) {
        e.printStackTrace();
    }


    String formatted = output.format(d);
    customViewHolder.articleTime.setText(formatted);
    customViewHolder.articleAuthor.setText(article.getSource().getName());
    customViewHolder.articleTitle.setText(article.getTitle());
    Picasso.get().load(article.getUrlToImage()).into(customViewHolder.articleImage);
    customViewHolder.itemView.setOnClickListener(v -> {
        Intent intent = new Intent(v.getContext(), DetailActivity.class);

        intent.putExtra("urlKey", article.getUrl());

        v.getContext().startActivity(intent);

    });
    customViewHolder.articleShare.setOnClickListener(v -> {
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        String articleDescription = article.getDescription();
        String articleTitle = article.getTitle();
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, articleDescription);
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, articleTitle);
        v.getContext().startActivity((Intent.createChooser(sharingIntent, "Share using")));


    });

    customViewHolder.articleFavorite.setOnClickListener(v -> {
        myClipboard = (ClipboardManager) v.getContext().getSystemService(Context.CLIPBOARD_SERVICE);


        myClip = ClipData.newPlainText("label", customViewHolder.articleTitle.getText().toString());
        myClipboard.setPrimaryClip(myClip);
        Toast.makeText(v.getContext(), "Copied to clipboard", Toast.LENGTH_SHORT).show();

    });
}


@Override
public int getItemCount() {
    if (articles == null) return 0;
    return articles.size();
}

public interface ClickListener {
}

public class CustomViewHolder extends RecyclerView.ViewHolder {
    @BindView(R.id.articleAuthor)
    TextView articleAuthor;
    @BindView(R.id.articleTitle)
    TextView articleTitle;
    @BindView(R.id.articleImage)
    ImageView articleImage;
    @BindView(R.id.articleTime)
    TextView articleTime;
    @BindView(R.id.articleShare)
    ImageButton articleShare;
    @BindView(R.id.articleFavorite)
    ImageButton articleFavorite;

    public CustomViewHolder(View view) {
        super(view);
        ButterKnife.bind(this, view);


    }
}


}

在main.xml下面

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_search_white"
        android:title="@string/search_hint"
        app:showAsAction="collapseActionView|ifRoom"
        app:actionViewClass="android.support.v7.widget.SearchView" />
</menu>

跟随screeshot of recyclerview item in navgation drawer fragment

1 个答案:

答案 0 :(得分:0)

很抱歉,您无法及时回复,但似乎您正在一次调用这两个API。 一个用于获取所有数据,另一个用于获取包含一些字符串的过滤数据(例如,在您的代码中,您使用“ q”)。

您需要从Fragment的onCreateView中删除以下几行。单击搜索图标后才能调用它。并将 searchInterface.getSearchViewArticles(“ q”); 中的参数“ q”替换为将从搜索框中获取的字符串值。

    SportInterface searchInterface = SportClient.getApiService();
    Call<Search> searchCall = searchInterface.getSearchViewArticles("q");
    searchCall.enqueue(new Callback<Search>() {
        @Override
        public void onResponse(Call<Search> call, Response<Search> response) {
            search = response.body();

            if (search != null && search.getArticles() != null) {
                articleList.clear();
                articleList.addAll(search.getArticles());
            }

            if(articleAdapter != null){
                articleAdapter.notifyDataSetChanged();
            } else {
                articleAdapter = new ArticleAdapter(articleList, search);
                RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
                recyclerView.setLayoutManager(layoutManager);
                recyclerView.setAdapter(articleAdapter);
            }
        }

        @Override
        public void onFailure(Call<Search> call, Throwable t) {

        }
    });