Android uses the recycleview list implementation to load more sample code

Time:2021-9-22
catalogue
  • 1. Interface layout
  • 2. Function realization

1. Interface layout

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    android:background="#f0f3f5"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@mipmap/logo"/>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:orientation="vertical">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:gravity="center">

                <TextView
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    Android: text = "movie name" / >
                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        Android: text = "movie rating" / >

                </LinearLayout>
                <TextView
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:layout_height="wrap_content"
                    Android: text = "movie picture" / >
            </LinearLayout>

        </LinearLayout>
        <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:id="@+id/s1">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/r1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />


        </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
    </LinearLayout>

</FrameLayout>

List layout list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="160dp">
    <TextView
        android:id="@+id/t2"
        android:layout_width="0dp"
        android:layout_weight="1.5"
        android:gravity="center"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        Android: text = "I'm not a god of medicine" / >
    <TextView
        android:id="@+id/t3"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="9.0"/>
    <ImageView
        android:id="@+id/i1"
        android:layout_width="0dp"
        android:layout_weight="1.5"
        android:layout_height="150dp"
        android:padding="20dp"
        android:src="@mipmap/ic_launcher"/>
</LinearLayout>

Load more layout foot_ view.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          android:id="@+id/tv_foot"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:padding="10dp"
          android:gravity="center"
          Tools: text = "drop-down refresh"
          android:orientation="vertical"/>

在这里插入图片描述

2. Function realization

(1) Add network permissions


<uses-permission android:name="android.permission.INTERNET"/>

(2) Add third party libraries to use


  implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.squareup.okhttp3:okhttp:3.12.1'
    debugImplementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'

(3) Data analysis
Use the gsonformat plug-in to quickly convert the JSON string into a java bean, eliminating the process of handwritten corresponding java bean according to the JSON string.
Define a class onemodel.class


public class OneModel implements Serializable {

}

Use the shortcut key (ALT + s) to paste all the past data, and then keep clicking OK

在这里插入图片描述

(4) Bind control ID


private RecyclerView r1;
private SwipeRefreshLayout s1;
private LinearLayoutManager linearLayoutManager;
private Adapter adapter;

在这里插入图片描述

(5) Define an adapter class

package com.example.note4;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
    private Context mContext;
    private List<DateModel.SubjectsBean> mData;// data
    private int max_ count = 6;// Maximum number of displays
    private Boolean isFootView = false;// Footview added
    private String footViewText = "";// Contents of footview

    //The two final int types represent the two types of viewtype
    private final int NORMAL_TYPE = 0;
    private final int FOOT_TYPE = 1111;


    public Adapter(Context context, List<DateModel.SubjectsBean> data) {
        this.mContext = context;
        this.mData = data;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView t3,t2;
        public ImageView i1;
        private TextView tvFootView;

        //Initialize viewholder. After binding here, it can be directly used in onbindviewholder
        public ViewHolder(View itemView, int viewType) {
            super(itemView);
            if (viewType == NORMAL_TYPE) {
                t3 = (TextView) itemView.findViewById(R.id.t3);
                t2 = (TextView) itemView.findViewById(R.id.t2);
                i1=(ImageView)itemView.findViewById(R.id.i1);
            } else if (viewType == FOOT_TYPE) {
                tvFootView = (TextView) itemView.findViewById(R.id.tv_foot);
            }
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View normal_views = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.list, parent, false);
        View foot_view = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.foot_view, parent, false);

        if (viewType == FOOT_TYPE)
            return new ViewHolder(foot_view, FOOT_TYPE);
        return new ViewHolder(normal_views, NORMAL_TYPE);
    }

    @Override
    public int getItemViewType(int position) {
        if (position == max_count - 1) {
            return FOOT_TYPE;
        }
        return NORMAL_TYPE;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        DateModel.SubjectsBean subjectsBean=mData.get(position);
        //If footview exists and the current location viewtype is foot_ TYPE
        if (isFootView && (getItemViewType(position) == FOOT_TYPE)) {
            holder.tvFootView.setText(footViewText);
            //Refresh is too fast, so use hanlder to delay two seconds
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    max_count += 5;
                    notifyDataSetChanged();
                }
            }, 1000);

        } else {
            holder.t2.setText(subjectsBean.getTitle());
            holder.t3.setText(subjectsBean.getRate());
            Glide.with(mContext).load(subjectsBean.getCover()).into(holder.i1);
        }
    }

    @Override
    public int getItemCount() {
        if (mData.size() <= max_count) {
            return mData.size();
        }
        return max_count;
    }

    //Create a method to set text in footview
    public void setFootViewText(String footViewText) {
        isFootView = true;
        this.footViewText = footViewText;
    }

}

(6) Network request

public void getDate(DateModel dateModel)
    {
        if(dateModel==null||dateModel.getSubjects()==null)
        {
            Toast. Maketext (mainactivity. This, "failed", toast. Length_short). Show();
            return;
        }
        Toast. Maketext (mainactivity. This, "success", toast. Length_short). Show();
        adapter=new Adapter(MainActivity.this,dateModel.getSubjects());
        Adapter.setfootviewtext ("loading...);
        r1.setAdapter(adapter);
        s1.setRefreshing(false);
    }
    public void requestDate() {

        String url = "https://movie.douban.com/j/search_subjects?type=movie&tag=%E8%B1%86%E7%93%A3%E9%AB%98%E5%88%86&sort=recommend&page_limit=200&page_start=0";
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast. Maketext (mainactivity. This, "network connection failure", toast. Length_short). Show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Gson gson = new Gson();
                final DateModel dateModel = gson.fromJson(result, DateModel.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast. Maketext (mainactivity. This, "network connection succeeded", toast. Length_short). Show();
                        getDate(dateModel);
                    }
                });
            }
        });
    }

(7) Function realization

在这里插入图片描述


linearLayoutManager=new LinearLayoutManager(MainActivity.this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        r1.setLayoutManager(linearLayoutManager);
        requestDate();

        s1.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        requestDate();
                    }
                },1000);
            }
        });

(8) Source code
Click download

This is the end of this article about Android using the recycleview list to load more. For more information about Android loading, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]