天天看點

RecyclerView實作下拉重新整理添加條目1.添加控件SwipeRefreshLayout2.在MainActivity中實作重新整理操作完整代碼

首先自己寫一個簡單的RecyclerView,這裡不再贅述,不會寫的請參考我的上篇文章

RecyclerView的簡單使用 超級詳細

接下來實作重新整理效果

1.添加控件SwipeRefreshLayout

如果找不到該控件,請在build.gradle中添加

implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.0.0'
           

如果報錯,請在File—>Project Structure—>app那裡點加号選擇Library Dependency

搜尋swiperefreshlayout,選擇anroidx開頭的GroupID即可

RecyclerView實作下拉重新整理添加條目1.添加控件SwipeRefreshLayout2.在MainActivity中實作重新整理操作完整代碼

添加SwipeRefreshLayout并且建立id

res/layout下的activity_main.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">
    
       <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</RelativeLayout>
           

2.在MainActivity中實作重新整理操作

首先找到重新整理控件

在MainActivity中建立成員變量

在OnCreate()中綁定重新整理控件,并執行重新整理方法

mswipeRefreshLayout = findViewById(R.id.refresh_layout);
handlerDownPullUpdate();
           

建立重新整理方法,完成重新整理操作

private void handlerDownPullUpdate() {
		//設定重新整理的轉圈的顔色
        mswipeRefreshLayout.setColorSchemeResources(R.color.colorAccent,R.color.colorPrimary);
        //設定可用
        mswipeRefreshLayout.setEnabled(true);
        //重新整理操作監聽
        mswipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //在這裡面執行重新整理資料的操作
                /**
                 * 當我們在頂部下拉的時候,這個方法就會被執行
                 *  但是這個方法是MainThread是主線程,不可以執行耗時操作
                 *  一般來說,我們請求資料要開一個線程去擷取
                 *  //這裡面示範,直接添加資料
                 */

                ItemBean data = new ItemBean();
                data.title = "this is a sample which is newly added";
                data.icon = R.mipmap.sample_1;
                mdata.add(0,data);
                //更新UI,我們假裝卡3秒再添加資料
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //這裡做兩件事,1.讓重新整理停止 2.更新清單
                        listViewAdapter.notifyDataSetChanged();
                        mswipeRefreshLayout.setRefreshing(false);
                    }
                },3000);
            }
        });
    }
           

效果圖

RecyclerView實作下拉重新整理添加條目1.添加控件SwipeRefreshLayout2.在MainActivity中實作重新整理操作完整代碼

可以看到,每下拉重新整理一次,就有一個新的圖檔添加,且重新整理的小圓圈的顔色就是我們設定的顔色

完整代碼

MainActivity.java

package com.example.simplerecycler;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.Bundle;
import android.os.Handler;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

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

import adapter.ListViewAdapter;
import entity.ItemBean;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private List<ItemBean> mdata;
    public static int[] icons = {
            R.mipmap.sample_0,
            R.mipmap.sample_1,
            R.mipmap.sample_2,
            R.mipmap.sample_3,
            R.mipmap.sample_4,
            R.mipmap.sample_5,
            R.mipmap.sample_6,
            R.mipmap.sample_7,
    };    //存放圖檔資源的id
    private SwipeRefreshLayout mswipeRefreshLayout;
    private ListViewAdapter listViewAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //找到控件
        recyclerView = findViewById(R.id.recycler_view);
        //準備資料
        initData();

        listViewAdapter = new ListViewAdapter(mdata);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);


        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,2,GridLayoutManager.VERTICAL,false);

        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(3,GridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);

        recyclerView.setAdapter(listViewAdapter);

        mswipeRefreshLayout = findViewById(R.id.refresh_layout);


        handlerDownPullUpdate();
    }

    private void handlerDownPullUpdate() {
        mswipeRefreshLayout.setColorSchemeResources(R.color.colorAccent,R.color.colorPrimary);
        mswipeRefreshLayout.setEnabled(true);
        mswipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //在這裡面執行重新整理資料的操作
                /**
                 * 當我們在頂部下拉的時候,這個方法就會被執行
                 *  但是這個方法是MainThread是主線程,不可以執行耗時操作
                 *  一般來說,我們請求資料要開一個線程去擷取
                 *  //這裡面示範,直接添加資料
                 */

                ItemBean data = new ItemBean();
                data.title = "this is a sample which is newly added";
                data.icon = R.mipmap.sample_1;
                mdata.add(0,data);
                //更新UI
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //這裡做兩件事,1.讓重新整理停止 2.更新清單
                        listViewAdapter.notifyDataSetChanged();
                        mswipeRefreshLayout.setRefreshing(false);
                    }
                },3000);
            }
        });
    }

    private void initData() {
        //建立集合
        mdata = new ArrayList<>();
        //建立資料
        for (int i = 0; i < MainActivity.icons.length; i++) {
            //建立資料對象
            ItemBean data = new ItemBean();
            data.icon = MainActivity.icons[i];
            data.title = "第" + i + "條目";
            mdata.add(data);
        }
    }
}
           

ItemBean.java

package entity;

public class ItemBean {
    public int icon;
    public String title;
}
           

ListViewAdapter

public class ListViewAdapter extends RecyclerView.Adapter<ListViewAdapter.InnerHolder> {

    private List<ItemBean> mData;

    public ListViewAdapter(List<ItemBean> mData) {
        this.mData = mData;
    }

    @NonNull
    @Override
    public InnerHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = View.inflate(parent.getContext(),R.layout.item_list_view,null);
        return new InnerHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull InnerHolder holder, int position) {
        holder.setData(mData.get(position));
    }

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

    public class InnerHolder extends RecyclerView.ViewHolder {

        private ImageView icon;
        private TextView title;

        public InnerHolder(@NonNull View itemView) {
            super(itemView);
            icon = itemView.findViewById(R.id.icon);
            title = itemView.findViewById(R.id.title);
        }

        public void setData(ItemBean itemBean) {
            icon.setImageResource(itemBean.icon);
            title.setText(itemBean.title);
        }
    }
}
           

接下來是布局檔案

activity_main.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">


    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</RelativeLayout>
           

item_list_view.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
        app:cardUseCompatPadding="true"
        android:background="#fff">
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <ImageView
                android:id="@+id/icon"
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:src="@mipmap/sample_0"
                android:scaleType="fitXY"/>
            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="我是文本"
                android:layout_toRightOf="@+id/icon"
                android:textSize="25dp"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"/>
        </RelativeLayout>
    </androidx.cardview.widget.CardView>


</RelativeLayout>
           

本文參考自Bilibili UP主程式員拉大鋸 他的視訊講解的更加全面,如需了解,請跳轉至

【安卓常用控件】RecyclerView-程式員拉大鋸

如果up主看我不爽,請聯系我删除。。。。