简体   繁体   中英

Display separate View (image+text) when RecyclerView is empty

I need to display a View with an image and some text when my RecyclerView is empty. The code I have is doing the job but I think there is a better way to do it. I saw some things like the visibility of a view but most examples are for a TextView only.

Here is my code:

Note that for the xml file, if I set visibility:gone for the empty_view, I never see the empty_view. And if I delete this line I always see the empty_view

<?xml version="1.0" encoding="utf-8"?><!--
  As recommended by Google, we use a ConstraintLayout
  as the root element
  We add a padding all around using the padding attribute
-->
<androidx.constraintlayout.widget.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=".CityActivity"
    >

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />

    <include
        android:id="@+id/empty_view"
        layout="@layout/activity_city_empty"
        />


    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_add_location"
        app:backgroundTint="@color/orange"
        app:fabSize="normal"
        android:layout_margin="12dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        />


</androidx.constraintlayout.widget.ConstraintLayout>

And here is my main activity:

    public class CityActivity extends AppCompatActivity implements OnClickListener {


    private RecyclerView recyclerView;

    private ConstraintLayout mEmptyLayout;

    public static final String TAG = CityActivity.class.getSimpleName();



    /*
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final List<City> cities = CityRepository.getInstance(this).getCities();
        /*if(cities.isEmpty())
        {
            setContentView(R.layout.activity_city_empty);
        }
        else {
            setContentView(R.layout.activity_city);
            recyclerView = findViewById(R.id.recyclerView);
            recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        //}
        mEmptyView = findViewById(R.id.empty_view);
        //We configure the click on the fab
        findViewById(R.id.fab).setOnClickListener(this);
    }*/



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

        recyclerView = findViewById(R.id.recyclerView);
        mEmptyLayout = findViewById(R.id.empty_view);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        findViewById(R.id.fab).setOnClickListener(this);
        setup();
    }

    private void setup() {
        final List<City> cities = CityRepository.getInstance(this).getCities();
        final CitiesAdapter citiesAdapter = new CitiesAdapter(cities);
        recyclerView.setAdapter(citiesAdapter);

        citiesAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                checkIsEmpty(citiesAdapter);
            }
        });
    }


    @Override
    protected void onResume()
    {
        super.onResume();
        Log.d(TAG, "test");
        //We init the list into the onResume method
        //so the list is updated each time the screen goes to foreground
        setup();
    }

    private void initList(){
        //We retrieve the list of cities to display
        final List<City> cities = CityRepository.getInstance(this).getCities();
        //We create the adapter and we attach it to the RecyclerView
        final CitiesAdapter citiesAdapter = new CitiesAdapter(cities);
        recyclerView.setAdapter(citiesAdapter);
        citiesAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                checkIsEmpty(citiesAdapter);
            }
        });

    }

    @Override
    public void onClick(View v){
        final Intent intent = new Intent(this, AddCityActivity.class);
        startActivity(intent);
    }

    private void checkIsEmpty(CitiesAdapter citiesadapter) {
        mEmptyLayout.setVisibility(citiesadapter == null || citiesadapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
    }
}

Note:This is note my full code for the classes but I think these are the most important part for this problem.

Add an id to your include:

<include
android:id="@+id/empty_view"
layout="@layout/activity_city_empty"
        />

Inside the activity:

private RecyclerView recyclerView;
private View mEmptyView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO: Implement this method
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        mEmptyLayout = findViewById(R.id.empty_view);
        
        setup();
        
    }

The setup method:

private void setup() {
        final List<City> cities = CityRepository.getInstance(this).getCities();
        final CitiesAdapter citiesAdapter = new CitiesAdapter(cities);
        recyclerView.setAdapter(citiesAdapter);
        
        citiesAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
                @Override
                public void onChanged() {
                    super.onChanged();
                    checkIsEmpty();
                }
            });
    }
private void checkIsEmpty() {
            mEmptyView.setVisibility(mAdapter == null || mAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
    }

Results from previous example: 在此处输入图片说明

在此处输入图片说明

All the above answers can do the job but not in the proper and most clean way. Here is a extension of the RecyclerView that can handle an empty state.

public class ExtendedRecyclerView extends RecyclerView {

    private View mEmptyView;

    private AdapterDataObserver mDataObserver = new AdapterDataObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            updateEmptyView();
        }
    };

    public ExtendedRecyclerView (Context context) {
        super(context);
    }

    public ExtendedRecyclerView (Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ExtendedRecyclerView (Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * Designate a view as the empty view. When the backing adapter has no
     * data this view will be made visible and the recycler view hidden.
     */
    public void setEmptyView(View emptyView) {
        mEmptyView = emptyView;
    }

    @Override
    public void setAdapter(RecyclerView.Adapter adapter) {
        if (getAdapter() != null) {
            getAdapter().unregisterAdapterDataObserver(mDataObserver);
        }
        if (adapter != null) {
            adapter.registerAdapterDataObserver(mDataObserver);
        }
        super.setAdapter(adapter);
        updateEmptyView();
    }

    private void updateEmptyView() {
        if (mEmptyView != null && getAdapter() != null) {
            boolean showEmptyView = getAdapter().getItemCount() == 0;
            mEmptyView.setVisibility(showEmptyView ? VISIBLE : GONE);
            setVisibility(showEmptyView ? GONE : VISIBLE);
        }
    }

}

In your activity class add the following to show the empty view.

public class MyActivity extends AppCompatActivity {

    ExtendedRecyclerView recycler_view;
    View empty_view;

    Adapter adapter;

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

        recycler_view = findViewById(R.id.recycler_view);
        empty_view = findViewById(R.id.empty_view);

        recycler_view.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        recycler_view.setLayoutManager(linearLayoutManager);
        adapter = new Adapter(getActivity(), myRandomList, false);
        recycler_view.setAdapter(adapter);
        recycler_view.setEmptyView(empty_view);

    }
}

In your fragement class add the following to show the empty view.

public class MyFragment extends Fragment {

    ExtendedRecyclerView recycler_view;
    View empty_view;

    Adapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container, false);

        recycler_view = view.findViewById(R.id.recycler_view);
        empty_view = view.findViewById(R.id.empty_view);

        recycler_view.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        recycler_view.setLayoutManager(linearLayoutManager);
        adapter = new Adapter(getActivity(), myRandomList, false);
        recycler_view.setAdapter(adapter);
        recycler_view.setEmptyView(empty_view);

        return view;
    }
}

Hope this helps you and anyone that comes across this answer! Happy Coding all!

I see where the problem lies exactly. Below is the correct code you need and it should work now. You forgot to declare your List as a new ArrayList and that caused the app to crash.

public class CityActivity extends AppCompatActivity {

        ExtendedRecyclerView recycler_view;
        View empty_view;

        CitiesAdapter citiesadapter;
        List<City> cities;

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

            recycler_view = findViewById(R.id.recyclerView);
            empty_view = findViewById(R.id.empty_view);

            cities = new ArrayList<>();

            recycler_view.setHasFixedSize(true);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
            recycler_view.setLayoutManager(linearLayoutManager);
            citiesadapter = new CitiesAdapter(cities);
            recycler_view.setAdapter(citiesadapter);
            recycler_view.setEmptyView(empty_view);

        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM