관리 메뉴

막내의 막무가내 프로그래밍 & 일상

[안드로이드] 리사이클러뷰 , 스와이프리프레쉬아웃 함께 사용 ( recyclerview, SwipeRefreshLayout) 본문

안드로이드/자바 & Previous

[안드로이드] 리사이클러뷰 , 스와이프리프레쉬아웃 함께 사용 ( recyclerview, SwipeRefreshLayout)

막무가내막내 2019. 8. 10. 12:06
728x90

 

 

리사이클러 뷰에서 처음 10개씩 데이터를 불러오는데 위에서 아래로 댕기면 새로고침,  마지막 아이템에서 아래에서 위로 댕기면 로딩 후 데이터를 10개 더 가져오는 것을 구현해봤고 포스팅을 할려고한다.

 

아래에서 위로 댕겨서 데이터를 더 불러오는 것은 밑 사이트를 참고했다.

http://www.devexchanges.info/2017/02/android-recyclerview-dynamically-load.html

 

Learn Programming Together: Android RecyclerView dynamically load more items when scroll to end with bottom ProgressBar

xxxxx

www.devexchanges.info

 

SwipeRefreshLayout과 함께 쓰니 에러도 많았고 디비 불러오는 것도 이상하게 불러와서 하면서 막히는 부분이 좀 있었는데 그 삽질들을 코드로 기록하고 나중에 또 사용하게 되면 참고할려고 한다. (저를 위한 포스팅이기 때문에 참고하실려는 분들이 읽으시기엔 부족한 부분이 많을거라 생각합니다.)

 

 

1. xml이다.  (프래그먼트xml, 아이템1.xml, 아이템2(로딩).xml 

<?xml version="1.0" encoding="utf-8"?>
<layout 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"
    tools:context=".fragments.community.Tab3CommunityFragment">

    <data>

        <variable
            name="activity"
            type="com.minjin.romang.fragments.community.Tab3CommunityFragment" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.design.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center_horizontal"
                    android:orientation="horizontal"
                    android:weightSum="1">

                    <Button
                        android:id="@+id/community_tab3_btn_notice"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="12dp"
                        android:layout_marginBottom="12dp"
                        android:layout_weight="0.7"
                        android:background="@color/colorMainPink"
                        android:onClick="@{activity::onNoticeButtonClick}"
                        android:text="[공지] 커뮤니티 이용 안내"
                        android:textColor="@color/colorWhite" />


                </LinearLayout>

                <android.support.v4.widget.SwipeRefreshLayout
                    android:id="@+id/community_tab3_swipelayout"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="top"
                    android:foregroundGravity="top">

                    <android.support.v7.widget.RecyclerView
                        android:id="@+id/community_tab3_recycler"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:clipToPadding="false"
                        tools:listitem="@layout/item_community_post" />
                </android.support.v4.widget.SwipeRefreshLayout>


            </LinearLayout>

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/community_tab3_fab_mywrite"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom|end"
                android:layout_marginRight="15dp"
                android:layout_marginBottom="100dp"
                android:backgroundTint="@color/colorOrange"
                android:onClick="@{activity::onMyWriteButtonClick}"
                app:borderWidth="0dp"
                app:fabCustomSize="@android:dimen/notification_large_icon_height"
                app:maxImageSize="@android:dimen/notification_large_icon_height"
                app:srcCompat="@drawable/ic_community_mypost" />

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/community_tab3_fab_write"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom|end"
                android:layout_margin="15dp"
                android:backgroundTint="@color/colorMainPink"
                android:onClick="@{activity::onWriteButtonClick}"
                app:borderWidth="0dp"
                app:fabCustomSize="@android:dimen/notification_large_icon_height"
                app:maxImageSize="@android:dimen/notification_large_icon_height"
                app:srcCompat="@drawable/ic_writing" />



        </android.support.design.widget.CoordinatorLayout>
    </LinearLayout>
</layout>

 

<?xml version="1.0" encoding="utf-8"?>
<layout 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"
    tools:context=".fragments.community.Tab3CommunityFragment">

    <data>

        <variable
            name="activity"
            type="com.minjin.romang.fragments.community.Tab3CommunityFragment" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.design.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center_horizontal"
                    android:orientation="horizontal"
                    android:weightSum="1">

                    <Button
                        android:id="@+id/community_tab3_btn_notice"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="12dp"
                        android:layout_marginBottom="12dp"
                        android:layout_weight="0.7"
                        android:background="@color/colorMainPink"
                        android:onClick="@{activity::onNoticeButtonClick}"
                        android:text="[공지] 커뮤니티 이용 안내"
                        android:textColor="@color/colorWhite" />


                </LinearLayout>

                <android.support.v4.widget.SwipeRefreshLayout
                    android:id="@+id/community_tab3_swipelayout"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="top"
                    android:foregroundGravity="top">

                    <android.support.v7.widget.RecyclerView
                        android:id="@+id/community_tab3_recycler"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:clipToPadding="false"
                        tools:listitem="@layout/item_community_post" />
                </android.support.v4.widget.SwipeRefreshLayout>


            </LinearLayout>

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/community_tab3_fab_mywrite"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom|end"
                android:layout_marginRight="15dp"
                android:layout_marginBottom="100dp"
                android:backgroundTint="@color/colorOrange"
                android:onClick="@{activity::onMyWriteButtonClick}"
                app:borderWidth="0dp"
                app:fabCustomSize="@android:dimen/notification_large_icon_height"
                app:maxImageSize="@android:dimen/notification_large_icon_height"
                app:srcCompat="@drawable/ic_community_mypost" />

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/community_tab3_fab_write"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom|end"
                android:layout_margin="15dp"
                android:backgroundTint="@color/colorMainPink"
                android:onClick="@{activity::onWriteButtonClick}"
                app:borderWidth="0dp"
                app:fabCustomSize="@android:dimen/notification_large_icon_height"
                app:maxImageSize="@android:dimen/notification_large_icon_height"
                app:srcCompat="@drawable/ic_writing" />



        </android.support.design.widget.CoordinatorLayout>
    </LinearLayout>
</layout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />

</LinearLayout>

 

 

 

2.  리사이클러뷰 어댑터 코드

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.minjin.romang.R;
import com.minjin.romang.activities.community.CommunityFullActivity;
import com.minjin.romang.model.CommunityPost;

import java.util.ArrayList;

import de.hdodenhof.circleimageview.CircleImageView;

public class CommunityPostAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    Context context;
    ArrayList<CommunityPost> items;
    private int visibleThreshold = 2;
    private int lastVisibleItem, totalItemCount;
    private boolean isLoading;
    private OnLoadMoreListener onLoadMoreListener;
    //putExtra Key
    static final String EXTRA_COMMUNITY_POST = "EXTRA_COMMUNITY_POST";
    //상수
    private final int VIEW_TYPE_ITEM = 0;
    private final int VIEW_TYPE_LOADING = 1;


    @Override
    public int getItemViewType(int position) { //null값인 경우 로딩타입
        return items.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
    }

    public CommunityPostAdapter(RecyclerView recyclerView, Context context, ArrayList<CommunityPost> items) {
        this.context = context;
        this.items = items;

        final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("체크 :::: " , "토탈카운트: " + totalItemCount + "  , 마지막으로보이는아이템: " + lastVisibleItem );
                totalItemCount = linearLayoutManager.getItemCount();
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                //로딩중이아니고 , 전체아이템수 <= 마지막에 보이는 아이템인덱스 + 화면에보이는개수(리사이클러뷰에 아이템이 5개씩 보이므로 5로 설정함
                if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                    if (onLoadMoreListener != null) {
                        onLoadMoreListener.onLoadMore();
                    }
                    isLoading = true;
                }
            }
        });
    }


    @NonNull
    @Override //로딩 뷰타입과 아이템 뷰타입으로 나뉨
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        if (viewType == VIEW_TYPE_ITEM) {
            View view = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.item_community_post, viewGroup, false);
            return  new CommunityPostViewHolder(view);
        }else if (viewType == VIEW_TYPE_LOADING) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_loading, viewGroup, false);
           return new LoadingViewHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int i) {
        if(holder instanceof CommunityPostViewHolder) {
            CommunityPostViewHolder communityPostViewHolder = (CommunityPostViewHolder) holder;
            CommunityPost model = items.get(i);
            if (model.getWriterGender().equals("남자")) {
                communityPostViewHolder.profileCircleImageView.setImageResource(R.drawable.ic_community_male_example);
            } else {
                communityPostViewHolder.profileCircleImageView.setImageResource(R.drawable.ic_community_girl_example);
            }
            communityPostViewHolder.contentTextView.setText(model.getTitle());
            communityPostViewHolder.dateTextView.setText(model.getDate());
            communityPostViewHolder.commentCountTextView.setText(model.getCommentList().size() + "");
            communityPostViewHolder.recommendCountTextView.setText(model.getLike() + "");
        }else if (holder instanceof LoadingViewHolder) {
            LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
            loadingViewHolder.progressBar.setIndeterminate(true);
        }

    }

    @Override
    public int getItemCount() {
        return items == null ? 0 :items.size();
    }

    public void setLoaded() {
        isLoading = false;
    }

    public void addItem(CommunityPost item) {
        items.add(item);
    }

    public void clear() {
        items.clear();
    }

    public class CommunityPostViewHolder extends RecyclerView.ViewHolder {
        CircleImageView profileCircleImageView;
        TextView contentTextView;
        TextView dateTextView;
        TextView commentCountTextView;
        TextView recommendCountTextView;
        LinearLayout linearLayout; //전체화면

        public CommunityPostViewHolder(@NonNull View itemView) {
            super(itemView);
            profileCircleImageView = itemView.findViewById(R.id.item_board_civ_profile);
            contentTextView = itemView.findViewById(R.id.item_board_tv_title);
            dateTextView = itemView.findViewById(R.id.item_board_tv_date);
            commentCountTextView = itemView.findViewById(R.id.item_board_tv_comment);
            recommendCountTextView = itemView.findViewById(R.id.item_board_tv_recommend);
            linearLayout = itemView.findViewById(R.id.item_board_linear);

            //작성글 풀화면
            linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        CommunityPost item = items.get(position);
                        Intent intent = new Intent(context, CommunityFullActivity.class);
                        intent.putExtra(EXTRA_COMMUNITY_POST, item);
                        context.startActivity(intent);
                    }
                }
            });
        }
    }

    // "Loading item" ViewHolder
    private class LoadingViewHolder extends RecyclerView.ViewHolder {
        public ProgressBar progressBar;

        public LoadingViewHolder(View view) {
            super(view);
            progressBar = (ProgressBar) view.findViewById(R.id.progressBar1);
        }
    }

    public interface OnLoadMoreListener {
        void onLoadMore();
    }

    public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
        this.onLoadMoreListener = mOnLoadMoreListener;
    }
}

 

 

 

3. 프래그먼트(자바코드)

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.minjin.romang.R;
import com.minjin.romang.activities.community.CommunityWriteActivity;
import com.minjin.romang.adapter.community.CommunityPostAdapter;
import com.minjin.romang.databinding.FragmentTab3CommunityBinding;
import com.minjin.romang.model.CommunityPost;
import com.minjin.romang.utils.FirebaseHelper;

import java.util.ArrayList;

//데이터바인딩 사용
public class Tab3CommunityFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    //TAG
    final static String TAG = "Tab3CommunityFragmentT";
    //파이어베이스
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    //value
    private ArrayList<CommunityPost> mPostArrayList;
    private CommunityPostAdapter mPostAdapter;
    FragmentTab3CommunityBinding layout;
    int size;
    public Tab3CommunityFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        layout = DataBindingUtil.inflate(inflater, R.layout.fragment_tab3_community, container, false);
        layout.setActivity(this); //위와같이 정의한것을 세팅해줌(가져와줌)
        mPostArrayList = new ArrayList<>();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        layout.communityTab3Recycler.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        layout.communityTab3Recycler.setLayoutManager(layoutManager);
        //어댑터연결
        mPostAdapter = new CommunityPostAdapter(layout.communityTab3Recycler, getActivity(), mPostArrayList);
        layout.communityTab3Recycler.setAdapter(mPostAdapter);
        loadPostFromDB();

        //스와이프시 새로고침
        layout.communityTab3Swipelayout.setOnRefreshListener(this);
        return layout.getRoot();
    }


    @Override
    public void onResume() {
        super.onResume();
        loadPostFromDB();
    }

    //데이터바인딩 온클릭
    public void onWriteButtonClick(View view) {
        Intent profileIntent = new Intent(getActivity(), CommunityWriteActivity.class);
        startActivity(profileIntent);
    }

    //내가작성한 글
    //TODO:: Caused by: io.grpc.StatusException: FAILED_PRECONDITION: The query requires an index. You can create it here: 에러가 계속 나서 찾아보니 orederBy랑 whereEqualTO랑
    //같이쓰면 에러가 나는 것 같음. 그래서      .orderBy("postUid", Query.Direction.DESCENDING)를 없에줬다. 그리고 내부적으로(코드로) 역순으로 해주었다.
    public void onMyWriteButtonClick(View view) {
        db.collection("CommunityPosts")
                .whereEqualTo("writerUid", FirebaseHelper.mUid)
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        mPostAdapter.clear();
                        mPostArrayList.clear();
                        ArrayList<CommunityPost> tmpPostArrayList = new ArrayList<>();
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                Log.d(TAG, document.getId() + " => " + document.getData());
                                CommunityPost communityPost = document.toObject(CommunityPost.class);
                                if (communityPost.getWriterUid().equals(FirebaseHelper.mUid)) { //내 uid와 같으면 내가 쓴 글
                                    tmpPostArrayList.add(communityPost);
                                }
                            }
                            //최신순서가 위로 오도록 맞추기위해 역순으로 데이터를 넣어주는 작업을한다.
                            for (int i = tmpPostArrayList.size() - 1; i >= 0; i--) {
                                mPostArrayList.add(tmpPostArrayList.get(i));
                            }
                            mPostAdapter.notifyDataSetChanged();
                            Toast.makeText(getActivity(), "내가 쓴 글", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                });
    }

    //공지 클릭
    public void onNoticeButtonClick(View view) {

    }

    //게시글 불러오기 (10개씩 불러온다)
    private void loadPostFromDB() {
        db.collection("CommunityPosts")
                .orderBy("postUid", Query.Direction.DESCENDING)
                .limit(10)
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            mPostArrayList.clear();
                            mPostAdapter.clear();
                            CommunityPost communityPost = null;
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                Log.d(TAG, document.getId() + " => " + document.getData().toString());
                                communityPost = document.toObject(CommunityPost.class);
                                Log.d(TAG, "디비로부터 불러온 값 : " + communityPost.getPostUid());
                                Log.d(TAG, "디비로부터 불러온 값 제목 : " + communityPost.getTitle());
                                mPostArrayList.add(communityPost);
                            }
                            mPostAdapter.notifyDataSetChanged();
                            //게시글 불러온 후 , 리사이클러뷰 마지막아이템까지 보이고 아래에서 위로 당기면 로딩 후 게시글을 더 불러오게 리스너를 설정해줌
                            mPostAdapter.setOnLoadMoreListener(new CommunityPostAdapter.OnLoadMoreListener() {
                                @Override
                                public void onLoadMore() {
                                    if (mPostArrayList.size() <= 1000) { //1000개 게시물까지 읽어올 수 있게했다.
                                        mPostArrayList.add(null); //null을 삽입하면 리사이클러뷰에서 뷰타입에서 로딩타입으로 인식하게 해놨다.
                                        mPostAdapter.notifyItemInserted(mPostArrayList.size() - 1);
                                        new Handler().postDelayed(new Runnable() { //2초후 게시글 불러오기 실행
                                            @Override
                                            public void run() {
                                                mPostArrayList.remove(mPostArrayList.size() - 1);  //로딩 들어갔던거를 빼준다.
                                                mPostAdapter.notifyItemRemoved(mPostArrayList.size());
                                                //Generating more data
                                                int index = mPostArrayList.size();
                                                String standard = mPostArrayList.get(index-1).getPostUid(); //마지막에 들어가 있는 데이터를 알아온다.
                                                loadMorePostFromDB(standard); // 그 값을 기준으로 DB에서 이후 값들을 불러온다.
                                            }
                                        }, 2000);
                                    } else {
                                        Toast.makeText(getActivity(), "Loading data completed", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                       layout.communityTab3Swipelayout.setRefreshing(false);
                    }
                });

    }

    //맨 마지막 게시물에서 화면 위로 당기면 게시글 추가로 더 불러오기
    private void loadMorePostFromDB(String standard) {
        db.collection("CommunityPosts")
                .orderBy("postUid", Query.Direction.DESCENDING)
                .startAfter(standard)
                .limit(10)
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            CommunityPost communityPost = null;
                            boolean hasDocument = false;
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                Log.d(TAG, document.getId() + " => " + document.getData().toString());
                                communityPost = document.toObject(CommunityPost.class);
                                Log.d(TAG, "디비로부터 불러온 값 : " + communityPost.getPostUid());
                                Log.d(TAG, "디비로부터 불러온 값 제목 : " + communityPost.getTitle());
                                mPostArrayList.add(communityPost);
                                hasDocument = true;
                            }
                            if(!hasDocument){ //문서가 없는 경우 마지막내용까지 읽어온 것이다.
                                Toast.makeText(getActivity(), "마지막 게시글입니다.", Toast.LENGTH_SHORT).show();
                            }
                            mPostAdapter.notifyDataSetChanged();
                            mPostAdapter.setLoaded();
                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                        layout.communityTab3Swipelayout.setRefreshing(false);
                    }
                });
    }


    @Override
    public void onRefresh() {
        mPostArrayList.clear();
        mPostAdapter.clear();
        removeScrollPullUpListener(); //스와이프와(위에서 아래로 댕기는 새로고침) 리사이클러뷰 포지션 리스너를 같이 쓰면 에러가나므로 리사이클러뷰 리스너는 잠시 끊어주고 새로고침후 다시연결해준다.
        loadPostFromDB(); // 디비에서 값을 다시불러온다.
        /*
         *  TODO:추후 3초에 한번만 새로고침가능한 로직 넣으면 좋을듯
         * */
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    private void removeScrollPullUpListener(){
        layout.communityTab3Recycler.removeOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            }
        });
    }


}

 

 

 

[결과화면]

위에서 아래로 땡긴경우

 

 

아래에서 위로 땡긴 경우

 

728x90
Comments