Android RecyclerView最全使用詳解

RecyclerView概述

RecyclerView是官方在5.0之後新添加的控件,推出用來替代傳統的ListViewGridView列表控件。

RecyclerView使用-基礎篇

第一步:添加RecyclerView

**方法1:**點開任意一個佈局文件,找到左邊的RecyclerView控件,點擊旁邊的按鈕即可添加RecyclerView
在這裏插入圖片描述
**方法2:**在build.gradle文件中添加依賴

    implementation 'androidx.recyclerview:recyclerview:1.1.0'

在這裏插入圖片描述

第二步:添加布局文件

在佈局文件activity_main.xml中先添加RecyclerView控件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

再添加一個item_list.xml的佈局文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="29dp"
        android:layout_marginTop="33dp"
        android:text="標題"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="4dp"
        android:layout_marginTop="18dp"
        android:text="內容"
        app:layout_constraintStart_toStartOf="@+id/textView"
        app:layout_constraintTop_toBottomOf="@+id/textView" />
</androidx.constraintlayout.widget.ConstraintLayout>

第三步:添加邏輯代碼

首先定一個實體類如下:

public class News {
    public String title; // 標題
    public String content; //內容
}

然後在MainActivity中定義內部類 ViewHolder類、 MyAdapter類以及設置RecyclerView相關邏輯

package com.lucashu.recyclerview;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

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

public class MainActivity extends AppCompatActivity {
    RecyclerView mRecyclerView;
    MyAdapter mMyAdapter ;
    List<News> mNewsList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = findViewById(R.id.recyclerview);
        // 構造一些數據
        for (int i = 0; i < 50; i++) {
            News news = new News();
            news.title = "標題" + i;
            news.content = "內容" + i;
            mNewsList.add(news);
        }
        mMyAdapter = new MyAdapter();
        mRecyclerView.setAdapter(mMyAdapter);
        LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
        mRecyclerView.setLayoutManager(layoutManager);
    }

    class MyAdapter extends RecyclerView.Adapter<MyViewHoder> {

        @NonNull
        @Override
        public MyViewHoder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = View.inflate(MainActivity.this, R.layout.item_list, null);
            MyViewHoder myViewHoder = new MyViewHoder(view);
            return myViewHoder;
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHoder holder, int position) {
            News news = mNewsList.get(position);
            holder.mTitleTv.setText(news.title);
            holder.mTitleContent.setText(news.content);
        }

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

    class MyViewHoder extends RecyclerView.ViewHolder {
        TextView mTitleTv;
        TextView mTitleContent;

        public MyViewHoder(@NonNull View itemView) {
            super(itemView);
            mTitleTv = itemView.findViewById(R.id.textView);
            mTitleContent = itemView.findViewById(R.id.textView2);
        }
    }
}

運行效果

在這裏插入圖片描述

RecyclerView使用-進階篇

佈局管理器

RecyclerView提供了三種佈局管理器即:

  • LinearLayoutManager 線性佈局管理器
  • StaggeredGridLayoutManager 瀑布流佈局管理器
  • GridLayoutManager 網格佈局管理器

線性佈局管理器

這三種佈局管理器都是通過setLayoutManager方法來設置
LinearLayoutManager 還可以設置橫向滾動,只需將前面MainActivity中的layoutManager加一句代碼即可:

 LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
 layoutManager.setOrientation(RecyclerView.HORIZONTAL);
 mRecyclerView.setLayoutManager(layoutManager);

在這裏插入圖片描述

網格佈局管理器

如果讓一行顯示多個,可以設置 GridLayoutManager網格佈局管理器來實現

  GridLayoutManager layoutManager = new GridLayoutManager(MainActivity.this,3);
//        layoutManager.setOrientation(RecyclerView.HORIZONTAL);  也能設置橫向滾動
  mRecyclerView.setLayoutManager(layoutManager);

在這裏插入圖片描述

ItemDecoration

通過給 設置ItemDecoration 來裝飾Item的效果,比如我們要設置間隔線

DividerItemDecoration mDivider = new    
                        DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
mRecyclerView.addItemDecoration(mDivider);

在這裏插入圖片描述

Item 動畫

RecyclerView提供了默認的ItemAnimator實現類:DefaultItemAnimator。該類可以幫我們實現一些炫酷的動畫效果

DefaultItemAnimator itemAnimator = new DefaultItemAnimator();
defaultItemAnimator.setAddDuration(1000);
defaultItemAnimator.setRemoveDuration(1000);
 mRecyclerView.setItemAnimator(itemAnimator);

MainActivity中添加了兩個按鈕, 一個添加item,一個刪除item

Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                News news = new News();
                news.title = "標題 新內容" ;
                news.content = "內容 新內容" ;
                mNewsList.add(1,news);
                mMyAdapter.notifyItemInserted(1);
            }
        });
        Button button1 = findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mNewsList.remove(0);
                mMyAdapter.notifyItemMoved(0,1);
            }
        });

效果如下:
在這裏插入圖片描述

Item 點擊

可以通過對整個Item文件的根佈局添加一個點擊事件來實現Item的點擊

在這裏插入圖片描述

在這裏插入圖片描述

效果如下:
在這裏插入圖片描述

RecyclerView使用-高級篇(上拉刷新下拉加載更多)

通常RecyclerView使用的時候需要配合上拉刷新下拉加載更多的功能
我們通過開源控件SmartRefreshLayout來實現
SmartRefreshLayout官網:https://github.com/scwang90/SmartRefreshLayout
使用方法如下:

第一步:添加依賴

在gradle文件中添加

implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.1.2'   
implementation 'com.scwang.smartrefresh:SmartRefreshHeader:1.1.2'  

第二步:佈局文件

activity_main.xmlSmartRefreshLayout控件將RecyclerView包裹起來

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <com.scwang.smartrefresh.layout.SmartRefreshLayout
        android:id="@+id/refreshLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerview"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </com.scwang.smartrefresh.layout.SmartRefreshLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

第三步:邏輯代碼

MainActivityonCreate方法中添加下拉刷新和上拉加載更多的功能

下拉刷新

RefreshLayout refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000/*,false*/);//傳入false表示刷新失敗
                mNewsList.clear();
                for (int i = 0; i < 10; i++) {
                    News news = new News();
                    news.title = "標題 新內容" + i;
                    news.content = "內容" + i;
                    mNewsList.add(news);
                }
                mMyAdapter.notifyDataSetChanged();
            }
        });

上拉加載更多

 refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//傳入false表示加載失敗
                for (int i = 0; i < 10; i++) {
                    News news = new News();
                    news.title = "標題 新內容" + i;
                    news.content = "內容" + i;
                    mNewsList.add(news);
                }
                mMyAdapter.notifyDataSetChanged();
            }
        });

效果如下:
在這裏插入圖片描述

完整代碼

MainActivity.java文件

package com.lucashu.recyclerview;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

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

public class MainActivity extends AppCompatActivity {
    RecyclerView mRecyclerView;
    MyAdapter mMyAdapter ;
    List<News> mNewsList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = findViewById(R.id.recyclerview);
        // 構造一些數據
        for (int i = 0; i < 10; i++) {
            News news = new News();
            news.title = "標題" + i;
            news.content = "內容" + i;
            mNewsList.add(news);
        }

        mMyAdapter = new MyAdapter();
        mRecyclerView.setAdapter(mMyAdapter);
        LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
        mRecyclerView.setLayoutManager(layoutManager);


        RefreshLayout refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000/*,false*/);//傳入false表示刷新失敗
                mNewsList.clear();
                for (int i = 0; i < 10; i++) {
                    News news = new News();
                    news.title = "標題 新內容" + i;
                    news.content = "內容" + i;
                    mNewsList.add(news);
                }
                mMyAdapter.notifyDataSetChanged();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//傳入false表示加載失敗
                for (int i = 0; i < 10; i++) {
                    News news = new News();
                    news.title = "標題 新內容" + i;
                    news.content = "內容" + i;
                    mNewsList.add(news);
                }
                mMyAdapter.notifyDataSetChanged();
            }
        });

    }

    class MyAdapter extends RecyclerView.Adapter<MyViewHoder> {

        @NonNull
        @Override
        public MyViewHoder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = View.inflate(MainActivity.this, R.layout.item_list, null);
            MyViewHoder myViewHoder = new MyViewHoder(view);
            return myViewHoder;
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHoder holder, final int position) {
            News news = mNewsList.get(position);
            holder.mTitleTv.setText(news.title);
            holder.mTitleContent.setText(news.content);
            holder.mRootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(MainActivity.this,"點擊了:"+ position,Toast.LENGTH_LONG).show();
                }
            });
        }

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

    class MyViewHoder extends RecyclerView.ViewHolder {
        TextView mTitleTv;
        TextView mTitleContent;
        ConstraintLayout mRootView;

        public MyViewHoder(@NonNull View itemView) {
            super(itemView);
            mTitleTv = itemView.findViewById(R.id.textView);
            mTitleContent = itemView.findViewById(R.id.textView2);
            mRootView = itemView.findViewById(R.id.rootview);
        }
    }
}

activity_main.xml文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <com.scwang.smartrefresh.layout.SmartRefreshLayout
        android:id="@+id/refreshLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </com.scwang.smartrefresh.layout.SmartRefreshLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章