如何在 android 中将 Layout 设置为 RecyclerView

How to set Layout to RecyclerView in android

我想从服务器加载数据并在我的应用程序中显示 (RecyclerView),对于此作业,当应用程序启动时它显示 10 posts 并且在滚动时显示 recyclerView显示另一个 post .

我写了下面的代码,但是当得到其他 10 posts 时,不显示 加载布局!我想当得到其他 10 posts 时,首先 show loading 布局然后显示其他 10 posts!

为了连接到互联网,我使用 Retrofit v2,对于 recyclerView 的自定义 Endless 方法,我使用这个 class: EndLess Class

我的Activity代码:

public class Category_page extends AppCompatActivity implements ConnectivityReceiver.ConnectivityReceiverListener {

    private static final long RIPPLE_DURATION = 250;
    private Toolbar toolbar;
    private TextView toolbar_title;
    private ImageView toolbar_menuImage;
    private Button categoryCheckNet_button;
    private RelativeLayout root;
    private CategoryAdapter mAdapter;
    private RecyclerView cat_recyclerView;
    private LinearLayoutManager mLayoutManager;
    private RelativeLayout loadLayout, checkNetLayout;
    private String catTitle = "";
    private Integer catID;
    private Bundle bundle;
    private int pageCount = 1;
    private Context context;

    private List<R_CatModel> models;

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

        // Hide StatusBar color
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

        // Initializing
        context = Category_page.this;
        toolbar = (Toolbar) findViewById(R.id.category_toolbar);
        cat_recyclerView = (RecyclerView) findViewById(R.id.category_recycler);
        toolbar_title = (TextView) toolbar.findViewById(R.id.toolbar_pages_title);
        mLayoutManager = new LinearLayoutManager(this);
        root = (RelativeLayout) findViewById(R.id.category_root);
        loadLayout = (RelativeLayout) findViewById(R.id.category_empty_layout);
        checkNetLayout = (RelativeLayout) findViewById(R.id.category_checkInternet_layout);
        categoryCheckNet_button = (Button) checkNetLayout.findViewById(R.id.checkNet_button);
        // Toolbar
        setSupportActionBar(toolbar);
        if (toolbar != null) {
            getSupportActionBar().setTitle("");
        }

        // Receive Data
        bundle = getIntent().getExtras();
        catID = bundle.getInt("categoryID");
        if (bundle != null) {
            catTitle = bundle.getString("categoryTitle");
        }
        if (catTitle != null) {
            toolbar_title.setText(catTitle);
        }

        // Load Data
        loadData();

        // Load Progress
        loadLayout.setVisibility(View.VISIBLE);

        // Menu
        View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
        root.addView(guillotineMenu);
        toolbar_menuImage = (ImageView) toolbar.findViewById(R.id.toolbar_pages_logo);
        new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), toolbar_menuImage)
                .setStartDelay(RIPPLE_DURATION)
                .setActionBarViewForAnimation(toolbar)
                .setClosedOnStart(true)
                .build();
        // RecyclerView
        cat_recyclerView.setLayoutManager(mLayoutManager);
        cat_recyclerView.setHasFixedSize(true);
        cat_recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
            @Override
            public void onLoadMore(int current_page) {

                Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
                Call<R_CatModelResponse> call = apiInterface.getCatMoreResponse(catID, current_page);

                call.enqueue(new Callback<R_CatModelResponse>() {
                    @Override
                    public void onResponse(Call<R_CatModelResponse> call, Response<R_CatModelResponse> response) {

                        if (response != null) {
                            mAdapter.addNewItem(response.body().getCat_posts());
                            //loadLayout.setVisibility(View.GONE);
                        } else {
                            //loadLayout.setVisibility(View.VISIBLE);
                            Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
                            TastyToast.makeText(context, "خطایی رخ داده است", TastyToast.LENGTH_LONG, TastyToast.ERROR);
                        }
                    }

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

                    }
                });
            }
        });

    }

    private void loadData() {
        boolean isConnected = ConnectivityReceiver.isConnected();

        retrofitData(isConnected);
    }

    private void retrofitData(boolean isConnect) {

        if (isConnect) {
            Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
            Call<R_CatModelResponse> call = apiInterface.getCatResponse(catID);

            call.enqueue(new Callback<R_CatModelResponse>() {
                @Override
                public void onResponse(Call<R_CatModelResponse> call, Response<R_CatModelResponse> response) {

                    if (response != null) {
                        models = response.body().getCat_posts();

                        mAdapter = new CategoryAdapter(context, cat_recyclerView, models);
                        cat_recyclerView.setAdapter(mAdapter);
                        loadLayout.setVisibility(View.GONE);

                    } else {
                        //loadLayout.setVisibility(View.VISIBLE);
                        Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
                        TastyToast.makeText(context, "خطایی رخ داده است", TastyToast.LENGTH_LONG, TastyToast.ERROR);
                    }

                    checkNetLayout.setVisibility(View.GONE);
                }

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

                    //loadLayout.setVisibility(View.VISIBLE);
                    //TastyToast.makeText(context, "لطفا برنامه را مجددا باز کنید", TastyToast.LENGTH_LONG, TastyToast.ERROR);
                    Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
                    //Cat_EmptyLayout.setVisibility(View.VISIBLE);
                    Log.e("CatResponseError", "Error : " + t);

                }
            });
        } else {
            //loadLayout.setVisibility(View.GONE);
            checkNetLayout.setVisibility(View.VISIBLE);
            if (mAdapter != null) {
                mAdapter.clear();
                cat_recyclerView.setAdapter(mAdapter);
            }
            categoryCheckNet_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    loadData();
                }
            });
        }
    }

    public void post_back(View view) {
        onBackPressed();
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

    @Override
    protected void onResume() {
        super.onResume();
        // register connection status listener
        MyApplication.getInstance().setConnectivityListener(this);
    }

    @Override
    public void onNetworkConnectionChanged(boolean isConnected) {
        retrofitData(isConnected);
    }
}

我的适配器代码:

public class CategoryAdapter extends RecyclerView.Adapter {

    private List<R_CatModel> mDateSet;
    private Context mContext;

    private final int VIEW_ITEM = 1;
    private final int VIEW_PROG = 0;

    // The minimum amount of items to have below your current scroll position
    // before loading more.
    private int visibleThreshold = 10;
    private int lastVisibleItem, totalItemCount;
    private boolean loading;
    private OnLoadMoreListener onLoadMoreListener;

    public CategoryAdapter(Context context, RecyclerView recyclerView, List<R_CatModel> dataSet) {
        this.mContext = context;
        this.mDateSet = dataSet;

        if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {

            final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView
                    .getLayoutManager();
            recyclerView
                    .addOnScrollListener(new RecyclerView.OnScrollListener() {
                        @Override
                        public void onScrolled(RecyclerView recyclerView,
                                               int dx, int dy) {
                            super.onScrolled(recyclerView, dx, dy);
                            totalItemCount = linearLayoutManager.getItemCount();
                            lastVisibleItem = linearLayoutManager
                                    .findLastVisibleItemPosition();
                            if (!loading
                                    && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                                // End has been reached
                                // Do something
                                if (onLoadMoreListener != null) {
                                    onLoadMoreListener.onLoadMore();
                                }
                                loading = true;
                            }
                        }
                    });
        }
    }

    @Override
    public int getItemViewType(int position) {
        return mDateSet.get(position) != null ? VIEW_ITEM : VIEW_PROG;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        RecyclerView.ViewHolder vh;
        if (viewType == VIEW_ITEM) {
            View v = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.post_card_layout, parent, false);

            vh = new DataViewHolder(v);
        } else {
            View v = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.progressbar_item, parent, false);

            vh = new ProgressViewHolder(v);
        }
        return vh;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {

        if (holder instanceof DataViewHolder) {
            ((DataViewHolder) holder).main_post_title.setText(Html.fromHtml(mDateSet.get(position).getTitle()));

            Glide.with(mContext)
                    .load(mDateSet.get(position).getThumbnail_images().getMedium().getUrl())
                    .placeholder(R.drawable.post_image)
                    .crossFade()
                    .override(600, 350)
                    .into(((DataViewHolder) holder).main_post_image);

            ((DataViewHolder) holder).main_post_content.setText(Html.fromHtml(mDateSet.get(position).getContent()));

            // Convert Date ////////
            String date = mDateSet.get(position).getDate();
            String[] parts = date.split(" ");
            String datePart = parts[0];
            String timePart = parts[1];

            int year;
            int month;
            int day;

            String[] dateParts = datePart.split("-");
            year = Integer.parseInt(dateParts[0]);
            month = Integer.parseInt(dateParts[1]);
            day = Integer.parseInt(dateParts[2]);

            JalaliCalendar.YearMonthDate georgianDate = new JalaliCalendar.YearMonthDate(year, month, day);
            JalaliCalendar.YearMonthDate JalaliDate = JalaliCalendar.gregorianToJalali(georgianDate);
            String jalaliDateTime = JalaliDate.toString();

            ((DataViewHolder) holder).main_dateTime.setText(jalaliDateTime);
            ////////////////////////

            ((DataViewHolder) holder).main_author.setText(Html.fromHtml(mDateSet.get(position).getCatAuthor().getAuthorName()));
            ((DataViewHolder) holder).main_author.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    R_CatModel model = mDateSet.get(position);
                    v.getContext().startActivity(new Intent(v.getContext(), Profile_page.class));
                    //.putExtra("author", model.getAuthor())
                    //.putExtra("authorID", model.getAuthorID())
                    //.putExtra("authorStatus", model.getAuthorStatus()));
                }
            });

            ((DataViewHolder) holder).main_category.setText(Html.fromHtml(String.valueOf(mDateSet.get(position).getCategories().get(0).getCatTitle())));
            ((DataViewHolder) holder).main_category.setTextColor(mContext.getResources().getColor(R.color.colorAccent));

            ((DataViewHolder) holder).main_post_image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos = holder.getPosition();
                    R_CatModel model = mDateSet.get(pos);
                    v.getContext().startActivity(new Intent(v.getContext(), PostShow_page.class)
                            .putExtra("title", model.getTitle())
                            .putExtra("image", model.getThumbnail())
                            .putExtra("content", model.getContent())
                            .putExtra("dateTime", model.getDate())
                            //.putExtra("author", model.getAuthor())
                            .putExtra("category", model.getTitle()));

                }
            });

        } else {
            ((ProgressViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
        }
    }

    public void setLoaded() {
        loading = false;
    }

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

    public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
        this.onLoadMoreListener = onLoadMoreListener;
    }

    public void remove(int position) {
        mDateSet.remove(position);
        notifyItemRemoved(position);
    }

    public void clear() {
        mDateSet.clear();
        notifyDataSetChanged();
    }

    public void addNewItem(List<R_CatModel> newContent) {
        int start = this.mDateSet.size();//contents is a List of your items initialize it your constructor
        int end = newContent.size();
        mDateSet.addAll(newContent);
        notifyItemRangeInserted(start + 1, end);
    }


    public void add(List<R_CatModel> models) {
        mDateSet.addAll(models);
        notifyDataSetChanged();
    }

    public void update(List<R_CatModel> models) {
        mDateSet.clear();
        mDateSet.addAll(models);
        notifyDataSetChanged();
    }

    public class DataViewHolder extends RecyclerView.ViewHolder {

        private TextView main_post_title, main_post_content, main_dateTime, main_author, main_category;
        private ImageView main_post_image;

        public DataViewHolder(final View itemView) {
            super(itemView);

            main_post_title = (TextView) itemView.findViewById(R.id.post_content_title);
            main_post_image = (ImageView) itemView.findViewById(R.id.post_picture_image);
            main_post_content = (TextView) itemView.findViewById(R.id.post_content_text);
            main_dateTime = (TextView) itemView.findViewById(R.id.post_date_text);
            main_author = (TextView) itemView.findViewById(R.id.post_name_text);
            main_category = (TextView) itemView.findViewById(R.id.post_category_text);
        }
    }

    public static class ProgressViewHolder extends RecyclerView.ViewHolder {
        public AVLoadingIndicatorView progressBar;

        public ProgressViewHolder(View v) {
            super(v);
            progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
        }
    }
}

我的Json:

{
    "status": "ok",
    "count": 9,
    "pages": 3,
    "category": {
        "id": 1,
        "slug": "%d8%b3%d8%b1%da%af%d8%b1%d9%85%db%8c",
        "title": "\u0633\u0631\u06af\u0631\u0645\u06cc",
        "description": "\u062a\u0648\u06cc \u0627\u06cc\u0646 \u06a9\u0644\u0648\u0646\u06cc \u0647\u0645\u0647 \u0686\u06cc\u0632 \u0648\u0627\u0633\u0647 \u0633\u0631\u06af\u0631\u0645 \u0628\u0648\u062f\u0646 \u0647\u0633\u062a. \u067e\u0633 \u0628\u062f\u0648 \u0628\u0631\u0648 \u062a\u0648\u0634",
        "parent": 0,
        "post_count": 29
    },
    "posts": [{
        "id": 85,
        "type": "post",
        "slug": "%d8%b9%d9%86%d9%88%d8%a7%d9%86-%d8%b3%d9%88%d9%85-%d8%a8%d8%b1%d8%a7%db%8c-%d8%b1%d9%81%d8%b1%d8%b4",
        "url": "http:\/\/tellfa.com\/tafrihgah\/?p=85",
        "status": "publish",
        "title": "\u0639\u0646\u0648\u0627\u0646 \u0633\u0648\u0645 \u0628\u0631\u0627\u06cc \u0631\u0641\u0631\u0634",
        "title_plain": "\u0639\u0646\u0648\u0627\u0646 \u0633\u0648\u0645 \u0628\u0631\u0627\u06cc \u0631\u0641\u0631\u0634",
        "content": "<p>\u062f\u06cc\u06af\u0647 \u0639\u0635\u0628\u0627\u0646\u06cc \u0634\u062f\u0645\u060c \u0686\u0631\u0627 \u0631\u0641\u0631\u0634 \u0646\u0645\u06cc\u06a9\u0646\u0647! :@<\/p>\n",
        "excerpt": "<p>\u062f\u06cc\u06af\u0647 \u0639\u0635\u0628\u0627\u0646\u06cc \u0634\u062f\u0645\u060c \u0686\u0631\u0627 \u0631\u0641\u0631\u0634 \u0646\u0645\u06cc\u06a9\u0646\u0647! :@<\/p>\n",
        "date": "2016-04-20 15:02:26",
        "modified": "2016-04-20 15:02:26",
        "categories": [{
            "id": 1,
            "slug": "%d8%b3%d8%b1%da%af%d8%b1%d9%85%db%8c",
            "title": "\u0633\u0631\u06af\u0631\u0645\u06cc",
            "description": "\u062a\u0648\u06cc \u0627\u06cc\u0646 \u06a9\u0644\u0648\u0646\u06cc \u0647\u0645\u0647 \u0686\u06cc\u0632 \u0648\u0627\u0633\u0647 \u0633\u0631\u06af\u0631\u0645 \u0628\u0648\u062f\u0646 \u0647\u0633\u062a. \u067e\u0633 \u0628\u062f\u0648 \u0628\u0631\u0648 \u062a\u0648\u0634",
            "parent": 0,
            "post_count": 29
        }],
        "tags": [],
        "author": {
            "id": 1,
            "slug": "tellfa",
            "name": "\u0645\u062d\u0645\u062f",
            "first_name": "",
            "last_name": "",
            "nickname": "\u0645\u062d\u0645\u062f",
            "url": "http:\/\/codesaz.com",
            "description": "\u0627\u06cc\u0646 \u0632\u0646\u062f\u06af\u06cc \u0646\u0627\u0645\u0647 \u0645\u0646 \u0627\u0633\u062a",
            "avatar": "76"
        },
        "comments": [],
        "attachments": [{
            "id": 86,
            "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024.jpg",
            "slug": "wallpapersmania_vol119-024",
            "title": "[WallpapersMania]_vol119-024",
            "description": "",
            "caption": "",
            "parent": 85,
            "mime_type": "image\/jpeg",
            "images": {
                "full": {
                    "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024.jpg",
                    "width": 1680,
                    "height": 1050
                },
                "thumbnail": {
                    "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-150x150.jpg",
                    "width": 150,
                    "height": 150
                },
                "medium": {
                    "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-300x188.jpg",
                    "width": 300,
                    "height": 188
                },
                "medium_large": {
                    "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-768x480.jpg",
                    "width": 768,
                    "height": 480
                }
            }
        }],
        "comment_count": 0,
        "comment_status": "open",
        "thumbnail": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-150x150.jpg",
        "custom_fields": {},
        "thumbnail_size": "thumbnail",
        "thumbnail_images": {
            "full": {
                "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024.jpg",
                "width": 1680,
                "height": 1050
            },
            "thumbnail": {
                "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-150x150.jpg",
                "width": 150,
                "height": 150
            },
            "medium": {
                "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-300x188.jpg",
                "width": 300,
                "height": 188
            },
            "medium_large": {
                "url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol119-024-768x480.jpg",
                "width": 768,
                "height": 480
            }
        }
    }

如何在获取其他 10 post 时显示加载布局?

您没有正确实施 getItemViewTypegetItemCount

@Override
public int getItemViewType(int position) {

    if (position < mDataSet.size()) {
        return VIEW_ITEM;
    }

    return VIEW_PROG;
}

@Override
public int getItemCount() {
    return mDateSet.size() + 1;
}

另外将 notifyItemRangeInserted(start + 1, end); 替换为 notifyDataSetChanged(); in addNewItem

编辑
在您的适配器中保留一个布尔值 private boolean hasMore = true 并像这样编辑 getItemCount()

@Override
public int getItemCount() {
    if (hasMore)
        return mDateSet.size() + 1;
    else 
        return mDataSet.size();
} 

你会有两种情况:
1. 如果您从之前的回复中知道没有更多的项目可以加载,请设置您的 hasMore = false .
2. 如果您不知道,那么在您的 Activity 中,当您在 onLoadMore 中得到响应时,如果 response== null || response.body() == null || response.body().getCat_posts().size() == 0 设置 hasMore = false.
这完全取决于您从服务器获得的响应
编辑
在你的适配器中添加一个方法

public void setHasMore(boolean hasMore) {
    this.hasMore = hasMore;
}

在 onLoadMore

call.enqueue(new Callback<R_CatModelResponse>() {
                    @Override
                    public void onResponse(Call<R_CatModelResponse> call, Response<R_CatModelResponse> response) {

                        if (response != null) {
                             adapter.setHasMore(response.body().getPages() !=current_page+1)
                             mAdapter.addNewItem(response.body().getCat_posts());
                            //loadLayout.setVisibility(View.GONE);
                        } else {
                            //loadLayout.setVisibility(View.VISIBLE);
                            Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
                            TastyToast.makeText(context, "خطایی رخ داده است", TastyToast.LENGTH_LONG, TastyToast.ERROR);
                        }
                    }

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

                    }
                });

使用 activity 布局中的进度条为 loadmore 创建一个布局,并将其可见性设置为 gone ,现在将 loadMore 布局的可见性设置为在 public void onLoadMore(int current_page) 方法并在您的网络服务响应中将其设置回 gone(在 onResponse 和 onFailure 方法中)

load_more.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/load_more"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#AA000000"
    android:gravity="center"
    android:visibility="gone"
    android:padding="5dp">

    <ProgressBar
        android:id="@+id/more_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/more_progress"
        android:padding="5dp"
        android:text="Loading results..."
        android:textColor="#ffffff"
        android:textSize="@dimen/medium_text_size" />

</RelativeLayout>

在你的 activity xml 文件中包含 load_more 就像 - listing_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:background="@color/listing_background"
    android:layout_height="match_parent">

<RelativeLayout
                android:layout_width="match_parent"
                android:layout_weight="1"
                android:layout_height="match_parent">
                <android.support.v7.widget.RecyclerView
                    android:id="@+id/recycleView"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:textSize="@dimen/medium_text_size"
                    android:gravity="center"
                    android:id="@+id/noListFound"
                    android:textColor="@color/orange"
                    android:text="No List found Please click here to add a new one"
                    android:visibility="gone"
                    android:padding="@dimen/header_margin"/>
            </RelativeLayout>

            <include layout="@layout/load_more"/>
        </LinearLayout>

BaseLoadMoreActivity.java

public abstract class BaseLoadMoreActivity extends Activity {
    @BindView(R.id.recycleView)
    RecyclerView recyclerView;
    @BindView(R.id.load_more)
    RelativeLayout loadMore;
    private LinearLayoutManager ll;
    private int page = 1;
    private boolean isNoData = false;
    private boolean isLoading = false;
    private RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (dy > 0) //check for scroll down
            {
                int visibleItemCount = ll.getChildCount();
                int totalItemCount = ll.getItemCount();
                int pastVisiblesItems = ll.findFirstVisibleItemPosition();

                if (!isLoading && !isNoData) {
                    if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                        loadMore.setVisibility(View.VISIBLE);
                        page++;
                        LoadMoreList();
                        isLoading = true;
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ll = new LinearLayoutManager(this);
        ll.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(ll);
        recyclerView.addOnScrollListener(scrollListener);

    }

    public abstract void LoadMoreList();
}

现在使用 BaseLoadMoreActivity 扩展您的 category_page.java 并更改代码

@Override
    public void LoadMoreList() {
        boolean isConnected = ConnectivityReceiver.isConnected();

        retrofitData(isConnected);
    }

private void retrofitData(boolean isConnect) {

        if (isConnect) {
            Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
            Call<R_CatModelResponse> call = apiInterface.getCatResponse(catID);

            call.enqueue(new Callback<R_CatModelResponse>() {
                @Override
                public void onResponse(Call<R_CatModelResponse> call, Response<R_CatModelResponse> response) {

                    if (response != null) {
                        models = response.body().getCat_posts();

                        mAdapter = new CategoryAdapter(context, cat_recyclerView, models);
                        cat_recyclerView.setAdapter(mAdapter);
                        loadMore.setVisibility(View.GONE);
                        isLoading = false;

                    } else {
                        loadMore.setVisibility(View.GONE);
                        isLoading = false;

                        Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
                        TastyToast.makeText(context, "خطایی رخ داده است", TastyToast.LENGTH_LONG, TastyToast.ERROR);
                    }

                    checkNetLayout.setVisibility(View.GONE);
                }

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

                    loadMore.setVisibility(View.GONE);
                        isLoading = false;

                    //TastyToast.makeText(context, "لطفا برنامه را مجددا باز کنید", TastyToast.LENGTH_LONG, TastyToast.ERROR);
                    Toast.makeText(Category_page.this, "Error 2", Toast.LENGTH_SHORT).show();
                    //Cat_EmptyLayout.setVisibility(View.VISIBLE);
                    Log.e("CatResponseError", "Error : " + t);

                }
            });
        } else {
            loadMore.setVisibility(View.GONE);
                        isLoading = false;

            checkNetLayout.setVisibility(View.VISIBLE);
            if (mAdapter != null) {
                mAdapter.clear();
                cat_recyclerView.setAdapter(mAdapter);
            }
            categoryCheckNet_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    loadData();
                }
            });
        }
    } 

请删除查找recycleView和设置它的布局管理器的代码 category_page.java 正如我们在 BaseLoadMoreActivity 中所做的那样,否则代码将无法运行。

我刚刚提供了示例代码。希望对您有所帮助...