当RecyclerView为空时,如何使SwipeRefreshLayout工作

时间:2019-06-16 12:58:28

标签: java android android-recyclerview swiperefreshlayout

我注意到SwipeRefreshLayout在我的RecyclerView充满数据时起作用,但在RecyclerView为空时却没有起作用。有没有办法覆盖这种行为?

我的应用程序从服务器获取了一些数据,并填充了RecyclerView。因此,举例来说,如果用户忘记了打开互联网但启动了我的应用程序,那么我希望他们能够将其打开并向上滑动以刷新,而不是返回并重新启动活动。

这是我的活动的xml。我删除了一些代码,以使其不再那么冗长。 SwipeRefreshLayout外面还有一个按钮,并且我也取消了约束。

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

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/b_swipe_refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_breakfast"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </android.support.v4.widget.SwipeRefreshLayout>

</android.support.constraint.ConstraintLayout>

这是.java文件:

public class BreakfastActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    // to display the menu
    RecyclerView rv_breakfast;
    RecyclerView.Adapter my_adapter;

    // the actual menu
    ArrayList<Menu> menu;

    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_breakfast);

        rv_breakfast = findViewById(R.id.rv_breakfast);
        swipeRefreshLayout = findViewById(R.id.b_swipe_refresh_layout);

        swipeRefreshLayout.setRefreshing(true);
        swipeRefreshLayout.setOnRefreshListener(this);

        rv_breakfast.setLayoutManager(new LinearLayoutManager(this));

        new GetMenu(this).execute();
    }

    @Override
    public void onRefresh() {
        new GetMenu(this).execute();
    }

    static class GetMenu extends GetMenuBase {

        WeakReference<BreakfastActivity> context;

        GetMenu(BreakfastActivity b) {
            context = new WeakReference<>(b);
            meal_type = "breakfast";
            b.swipeRefreshLayout.setRefreshing(true);
        }

        @Override
        protected void onPostExecute(JSONObject parent) {
            // process the output of the server side script script
            b.swipeRefreshLayout.setRefreshing(false);
        }
    }

java文件再次缺少一些与问题无关的代码。 GetMenuBase扩展AsyncTask并实现doInBackground()并调用服务器并返回JSON输出。

1 个答案:

答案 0 :(得分:1)

问题是,当您的RecyclerView为空时,您的身高将为0dp,因为您已将高度设置为wrap_content,并且将0dp设置为{{1 }}。

SwipeRefreshLayoutSwipeRefreshLayout的高度更改为RecyclerView