片段未显示整个recyclerview仅显示一张卡片视图

如何解决片段未显示整个recyclerview仅显示一张卡片视图

当我尝试从新闻API检索片段时,该片段仅显示一个cardview。 这是代码。

主要活动

package com.manish.newapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;

import com.google.android.material.tabs.TabLayout;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create an instance of the tab layout from the view.

        TabLayout tabLayout = findViewById(R.id.tab_layout);
        // Set the text for each tab.
        tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label1));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label2));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label3));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label4));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label5));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label6));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label7));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label8));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label9));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label10));

        // Set the tabs to scroll through the entire layout.
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

        // Use PagerAdapter to manage page views in fragments.
// Each page is represented by its own fragment.
        final ViewPager viewPager = findViewById(R.id.pager);
        final PagerAdapter adapter = new PagerAdapter
                (getSupportFragmentManager(),tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        // Setting a listener for clicks.
        viewPager.addOnPageChangeListener(new
                TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new
                                                   TabLayout.OnTabSelectedListener() {
                                                       @Override
                                                       public void onTabSelected(TabLayout.Tab tab) {
                                                           viewPager.setCurrentItem(tab.getPosition());
                                                       }

                                                       @Override
                                                       public void onTabUnselected(TabLayout.Tab tab) {
                                                       }

                                                       @Override
                                                       public void onTabReselected(TabLayout.Tab tab) {
                                                       }
                                                   });


    }
}

TabNews片段

package com.manish.newapp.Fragments;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.manish.newapp.Adapter;
import com.manish.newapp.ApiClient;
import com.manish.newapp.Models.Articles;
import com.manish.newapp.Models.Headlines;
import com.manish.newapp.Models.Source;
import com.manish.newapp.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TabNews1 extends Fragment {
    View v;
    RecyclerView recyclerView;
    final String API_KEY = "5a1ad719eee94e7ba60d19b51f4ff159";
    String sources = "bbc-news";
    Adapter adapter;
    List<Articles> articles = new ArrayList<>();





    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        String country = getCountry();
//        retrieveJson(country,API_KEY);


    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
        v=  inflater.inflate(R.layout.fragment_tab_news1,container,false);

        recyclerView = (RecyclerView)v.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        String country = getCountry();
        retrieveJson(country,API_KEY);
       // retrieveJson(sources,API_KEY);
        // Inflate the layout for this fragment
        return v;


    }
    public void retrieveJson(String country,String apiKey){
        Call<Headlines> call = ApiClient.getInstance().getApi().getHeadlines(country,apiKey);
        call.enqueue(new Callback<Headlines>() {
            @Override
            public void onResponse(Call<Headlines> call,Response<Headlines> response) {
                if (response.isSuccessful() && response.body().getArticles() != null){
                    articles.clear();
                    articles = response.body().getArticles();
                    adapter = new Adapter(getContext(),articles);
                    recyclerView.setAdapter(adapter);

                }

            }

            @Override
            public void onFailure(Call<Headlines> call,Throwable t) {
                Toast.makeText(getContext(),t.getLocalizedMessage(),Toast.LENGTH_SHORT).show();

            }
        });

    }

    public String getCountry(){
        Locale locale = Locale.getDefault();
        String country = locale.getCountry();
        return country.toLowerCase();

    }
}

适配器类

package com.manish.newapp;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.manish.newapp.Models.Articles;
import com.squareup.picasso.Picasso;

import java.util.List;

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {

    Context context;
    List<Articles> articles;

    public Adapter(Context context,List<Articles> articles) {
        this.context = context;
        this.articles = articles;
    }

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

    @Override
    public void onBindViewHolder(@NonNull Adapter.ViewHolder holder,int position) {
    Articles art = articles.get(position);
    holder.txtTitle.setText(art.getTitle());
    holder.txtDescription.setText(art.getDescription());
    holder.txtDate.setText(art.getPublishedAt());

    String imageUrl = art.getUrlToImage();

        Picasso.with(context).load(imageUrl).into(holder.imageView);
    }

    @Override
    public int getItemCount() {
        return articles.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView txtTitle,txtDescription,txtDate,txtTime;
        ImageView imageView;
        CardView cardView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            txtTitle = (TextView)itemView.findViewById(R.id.title_text);
            txtDescription = (TextView)itemView.findViewById(R.id.desc);
            txtTime = (TextView)itemView.findViewById(R.id.time);
            txtDate = (TextView)itemView.findViewById(R.id.date);

            imageView = (ImageView)itemView.findViewById(R.id.image_news);
            cardView = (CardView)itemView.findViewById(R.id.cardView);






        }
    }
}

Pager适配器类


import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;

import com.manish.newapp.Fragments.TabNews1;
import com.manish.newapp.Fragments.TabNews10;
import com.manish.newapp.Fragments.TabNews2;
import com.manish.newapp.Fragments.TabNews3;
import com.manish.newapp.Fragments.TabNews4;
import com.manish.newapp.Fragments.TabNews5;
import com.manish.newapp.Fragments.TabNews6;
import com.manish.newapp.Fragments.TabNews7;
import com.manish.newapp.Fragments.TabNews8;
import com.manish.newapp.Fragments.TabNews9;

public class PagerAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;
    public PagerAdapter(@NonNull FragmentManager fm,int NumOfTabs) {
        super(fm,NumOfTabs);
        this.mNumOfTabs = NumOfTabs;
    }


    @NonNull
    /**
     * Return the Fragment associated with a specified position.
     *
     * @param position
     */
    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0 : return new TabNews1();
            case 1 : return new TabNews2();
            case 2 : return new TabNews3();
            case 3 : return new TabNews4();
            case 4 : return new TabNews5();
            case 5 : return new TabNews6();
            case 6 : return new TabNews7();
            case 7 : return new TabNews8();
            case 8 : return new TabNews9();
            case 9 : return new TabNews10();
            default: return null;
        }

    }
    /**
     * Return the number of views available.
     */
    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}

这是我的布局文件。 item_recycler.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/cardView"
        android:layout_margin="16dp"
        android:padding="10dp"
        app:cardElevation="4dp"
        app:cardCornerRadius="10dp">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="8dp">
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:id="@+id/image_news"
                android:src="@drawable/image"
                android:scaleType="centerCrop"/>
<!--            <FrameLayout-->
<!--                android:layout_width="match_parent"-->
<!--                android:layout_height="wrap_content"-->
<!--                android:id="@+id/frame_layout"-->
<!--                android:layout_below="@+id/image_news"-->
<!--                android:padding="5dp">-->
<!--                <RelativeLayout-->
<!--                    android:layout_width="match_parent"-->
<!--                    android:layout_height="wrap_content">-->
                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="TITLE"
                        android:textSize="20dp"
                        android:layout_below="@+id/image_news"
                        android:textStyle="bold"
                        android:id="@+id/title_text"/>

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:id="@+id/desc"
                        android:text="DESCRIPTION"
                        android:layout_marginTop="10dp"
                        android:textSize="14dp"
                        android:layout_below="@+id/title_text"/>
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:id="@+id/time"
                        android:layout_below="@+id/desc"
                        android:text="TIME"
                        android:layout_marginTop="5dp"/>
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:id="@+id/date"
                        android:layout_below="@+id/time"
                        android:text="DATE"
                        android:layout_marginTop="5dp"/>
<!--                </RelativeLayout>-->
<!--            </FrameLayout>-->
        </RelativeLayout>
    </androidx.cardview.widget.CardView>
</RelativeLayout>

fragment_tab_news1.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Fragments.TabNews1"
    android:background="@color/colorBackground">

    <!-- TODO: Update blank fragment layout -->
    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">


<!--            <TextView-->
<!--                android:layout_width="match_parent"-->
<!--                android:layout_height="wrap_content"-->
<!--                android:text="BBC NEWS"-->
<!--                android:textStyle="bold"-->
<!--                android:textSize="17sp"-->
<!--                android:layout_marginLeft="16dp"-->
<!--                android:layout_marginRight="16dp"-->
<!--                android:layout_marginTop="10dp"-->
<!--                android:fontFamily="sans-serif-light"/>-->
<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/recycler_view"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

            </androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>

    </androidx.core.widget.NestedScrollView>



</RelativeLayout>

Mainactivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:id="@+id/relative_main"
    android:padding="16dp"
    >

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/toolbar"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
    <androidx.viewpager.widget.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/tab_layout"/>

</RelativeLayout>

请帮助我,我在这里找不到问题。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-