基于recyclerview的下拉刷新---SwipeRefreshLayout

1.效果展示

在这里插入图片描述

2.实现过程

(1)修改activity_main.xml,把SwipeRefreshLayout放在RecyclerView的外层,并把app:layout_behavior="@string/appbar_scrolling_view_behavior"这句代码放到SwipeRefreshLayout里。

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
       <!-- 避免被RecyclerView遮住-->
        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <!--自定义标题栏-->
            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:background="#969C99"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_scrollFlags="scroll|enterAlways|snap"
                /><!--当向上滚动时,toolbar会一起向上隐藏,否则会显示-->
        </com.google.android.material.appbar.AppBarLayout>

        <!--下拉刷新-->
        <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
            android:id="@+id/swipeRefresh"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">
            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/recyclerView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                />
        </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>


            <!-- 悬浮按钮-->
        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_margin="16dp"
            android:src="@drawable/yes"
            app:elevation="8dp"
           />

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

  <!--滑动自定义菜单-->
  <com.google.android.material.navigation.NavigationView
      android:id="@+id/navView"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_gravity="start"
      app:menu="@menu/nav_menu"
      app:headerLayout="@layout/nav_header"/>
</androidx.drawerlayout.widget.DrawerLayout>

(2)修改主活动,调用setOnRefreshListener()方法设置一个下拉刷新的监听器。

        //下拉刷新
        swipeRefresh=findViewById(R.id.swipeRefresh);
        swipeRefresh.setColorSchemeColors(R.color.colorPrimary);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshFruits();
            }
        });
    }

    private void refreshFruits(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    Thread.sleep(1000);//休眠1秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() { //切回主线程
                    @Override
                    public void run() {
                        iniFruits();
                        adapter.notifyDataSetChanged();//通知数据发生了变化
                        swipeRefresh.setRefreshing(false);//刷新结束
                    }
                });
            }
        }).start();

主活动全部代码:


import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 悬浮按钮和交互提示
 */
public class MainActivity extends AppCompatActivity {
    private DrawerLayout mDrawerLayout;
    private  Fruit[]fruits={new Fruit("苹果",R.drawable.nav_icon),
                            new Fruit("香蕉",R.drawable.t2),
                            new Fruit("西瓜",R.drawable.t5),
                            new Fruit("小丸子",R.drawable.touxiang),
                            new Fruit("小花",R.drawable.t8),
                            new Fruit("笨笨",R.drawable.t3),
    };
    private List<Fruit>fruitList=new ArrayList<>();
    private FruitAdapter adapter;
    private SwipeRefreshLayout swipeRefresh;
    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar=findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mDrawerLayout=findViewById(R.id.drawerLayout);
        NavigationView navigationView=findViewById(R.id.navView);
        FloatingActionButton fab=findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Snackbar.make(v,"删除",Snackbar.LENGTH_SHORT)
                        .setAction("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Toast.makeText(MainActivity.this,"已取消",Toast.LENGTH_SHORT).show();
                            }
                        }).show();
            }
        });
        ActionBar actionBar=getSupportActionBar();
        if (actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.menu);
        }
       // navigationView.setCheckedItem(R.id.navCall);//默认选中
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()){
                    case R.id.navCall:
                        Toast.makeText(MainActivity.this,"电话",Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.navFriends:
                        Toast.makeText(MainActivity.this,"朋友",Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.navLocation:
                        Toast.makeText(MainActivity.this,"地址",Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.nav_email:
                        Toast.makeText(MainActivity.this,"邮箱",Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.navTask:
                        Toast.makeText(MainActivity.this,"任务",Toast.LENGTH_SHORT).show();
                        break;
                }
                mDrawerLayout.closeDrawers();
                return true;
            }
        });
        iniFruits();
        RecyclerView recyclerView=findViewById(R.id.recyclerView);
        GridLayoutManager layoutManager=new GridLayoutManager(this,2);
        recyclerView.setLayoutManager(layoutManager);
        adapter=new FruitAdapter(fruitList);
        recyclerView.setAdapter(adapter);
        //下拉刷新
        swipeRefresh=findViewById(R.id.swipeRefresh);
        swipeRefresh.setColorSchemeColors(R.color.colorPrimary);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshFruits();
            }
        });
    }

    private void refreshFruits(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    Thread.sleep(1000);//休眠1秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() { //切回主线程
                    @Override
                    public void run() {
                        iniFruits();
                        adapter.notifyDataSetChanged();//通知数据发生了变化
                        swipeRefresh.setRefreshing(false);//刷新结束
                    }
                });
            }
        }).start();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.backup:
                Toast.makeText(this,"备份",Toast.LENGTH_SHORT).show();
                break;
            case R.id.delete:
                Toast.makeText(this,"删除",Toast.LENGTH_SHORT).show();
                break;
            case R.id.settings:
                Toast.makeText(this,"设置",Toast.LENGTH_SHORT).show();
                break;
            case R.id.back:
                Toast.makeText(this,"返回",Toast.LENGTH_SHORT).show();
                break;
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
        }
        return true;
    }
    private  void iniFruits(){
        fruitList.clear();
        for (int i=0;i<50;i++){
            Random random=new Random();
            int index=random.nextInt(fruits.length);
            fruitList.add(fruits[index]);
        }
    }
}

3.源码

4.参考资料:郭霖的《第一行代码》

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付 19.90元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值