美文网首页
Androidx RecyclerView(二 ): 下拉刷新

Androidx RecyclerView(二 ): 下拉刷新

作者: 中v中 | 来源:发表于2020-12-23 00:13 被阅读0次

    1.添加依赖

    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.0.0'
    
    1. 修改xml将RecyclerView包裹起来
    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
            android:id="@+id/main_refresh"
            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"
                tools:layout_editor_absoluteX="0dp"
                tools:layout_editor_absoluteY="0dp" />
        </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
    
    1. 修改activity的代码onCreate
    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_recycle);
    
            initCrush();
            CrushRecyclerView();
            // 下拉刷新组件及刷新
            mySwipeRefreshLayout = findViewById(R.id.main_refresh);
            mySwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    Toast.makeText(RecycleActivity.this,"刷新完成",Toast.LENGTH_LONG).show();
                    mySwipeRefreshLayout.setRefreshing(false);
    
                    // 改变数据
                    changeCrush();
                    // 通知adapter刷新数据
                    adapter.notifyDataSetChanged();
                }
            });
        }
    

    附件:changeCrush(),仅改变adapt的数据即可

    private void changeCrush() {
            crushList.clear();
            for (int i = 0; i < 2; i++) {
                Crush image0 = new Crush("change0", R.drawable.img0);
                crushList.add(image0);
                Crush image01 = new Crush("change1", R.drawable.img01);
                crushList.add(image01);
                Crush image02 = new Crush("change2", R.drawable.img02);
                crushList.add(image02);
                Crush image03 = new Crush("change3", R.drawable.img03);
                crushList.add(image03);
            }
        }
    

    相关文章

      网友评论

          本文标题:Androidx RecyclerView(二 ): 下拉刷新

          本文链接:https://www.haomeiwen.com/subject/xpnenktx.html