如何在 RecyclerView 为空时使 SwipeRefreshLayout 工作

How to make SwipeRefreshLayout work when the RecyclerView is empty

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

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

这是我的 activity 的 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() 并调用服务器和 returns JSON 输出。

问题是,当您的 RecyclerView 为空时,您的身高将是 0dp,因为您已将高度设置为 wrap_content 并将 0dp 设置为您的 SwipeRefreshLayout.

SwipeRefreshLayoutRecyclerView 的高度更改为 match_parent