안드로이드 심심풀이/응용

[안드로이드 스튜디오] RecyclerView 리로딩과 Fragment 새로고침

훈땅콩 2019. 7. 25. 17:30
반응형

안녕하세요! 오늘은 RecyclerView의 리로딩과 Fragment의 새로고침에 대해 포스팅 해보려 합니다!

 

인스타나 페이스북등에서 뷰 부분을 아래로 당길경우 리로딩이 되는데요! 그 부분에 것을 적어보도록 하겠습니다!

 

1. RecyclerView 리로딩

 

먼저 RecyclerView의 리로딩을 위해서는 

 

SwipeRefreshLayout으로 RecyclerView를 감싸줘야 합니다!

 <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
            android:id="@+id/swipe_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toBottomOf="@id/toolbar"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            >
            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/home_recyclerView"
                android:layout_width="match_parent"
                android:layout_height="0dp"
               >
            </androidx.recyclerview.widget.RecyclerView>
        </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

 

이런식으로 감싸주시면 되겠습니다!

 

다음으로는 사용하실 fragment나 activity에서 만들어 주시면 되는데요!

SwipeRefreshLayout mSwipeRefreshLayout = fv.findViewById(R.id.swipe_layout);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                ft.commit();
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                }, 500);

            }
        });

이런식으로 SwipeRefreshLayout을 선언해 주시고요!

 

onRefresh에서 새로고침시 사용할 소스코드를 적어주시면 됩니다! 

또한 setRefreshing(false);를 해주셔야 새로고침이 멈추기 때문에 꼭 해주셔야 합니다!

 

2. Fragment 새로고침

 

Fragment 새로고침은 매우 간단합니다! 단 두줄만 적어주시면 되는데요!

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(this).attach(this).commit;

이런식으로 적어주시면 되겠습니다! 감사합니다~

반응형