SwipeRefreshLayout с RecyclerView не работает во фрагменте - PullRequest
0 голосов
/ 20 мая 2019

У меня есть обзор переработчика внутри SwipeRefreshLayout во фрагменте.Я реализовал AsyncTask для получения данных для утилита-обзора.Проблема в том, что SwipeRefreshLayout не отображается вообще, и, следовательно, данные не заполняются в обзоре переработчика.Я сделал то же самое для Activity, и он работает просто отлично, но не фрагментарно.Кто-нибудь может подсказать мне, что я делаю не так?Это файл макета для фрагмента:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".FeatureFragment">

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        </androidx.recyclerview.widget.RecyclerView>

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</LinearLayout>

И вот что я сделал в классе фрагмента.

public class FeaturedFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout mSwipeLayout;
    public FeaturedFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_featured_captions, container, false);
        mRecyclerView = view.findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mSwipeLayout = view.findViewById(R.id.refresh_layout);
        mSwipeLayout.setOnRefreshListener(this);
        return view;
    }

    @Override
    public void onRefresh() {
        new FetchFeedTask().execute((Void) null);
    }


    private class FetchFeedTask extends AsyncTask<Void, Void, Boolean> {
        @Override
        protected void onPreExecute() {
            mSwipeLayout.setRefreshing(true);
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            //things to do in background
        }

        @Override
        protected void onPostExecute(Boolean success) {
            mSwipeLayout.setRefreshing(false);
            mRecyclerView.setAdapter(/*adapter*/);
            //things to do at the end
        }
    }

}

Ответы [ 3 ]

0 голосов
/ 20 мая 2019

Попробуйте использовать следующий фрагмент:

//Always use support library widgets. instead of these
 <androidx.recyclerview.widget.RecyclerView and
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeRefresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
            <android.support.v7.widget.RecyclerView
                android:id="@+id/recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
    </android.support.v4.widget.SwipeRefreshLayout>
0 голосов
/ 20 мая 2019

Измените высоту swipelayout на wrap_content

Решение 1 :)

 <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

Решение 2 :) Используйте разметку салфетки и вид переработчика с использованием библиотеки дизайна

<android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
         <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        />
    </android.support.v4.widget.SwipeRefreshLayout>
0 голосов
/ 20 мая 2019

Может ваш код не работает из-за ReacyclerView прокрутки Listener Попробуй ниже порезано.

mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener(){
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        int topRowVerticalPosition =
                (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
        mSwipeLayout.setEnabled(topRowVerticalPosition >= 0);

    }

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
    }
});

Кроме того, добавьте ваш материал инициализации внутри onViewCreated(), как показано ниже

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_featured_captions, container, false);
        return view;
    }



    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mRecyclerView = view.findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mSwipeLayout = view.findViewById(R.id.refresh_layout);
        mSwipeLayout.setOnRefreshListener(this);
   }
...