Step #7: Fixing the Empty Text

At this point, there are two situations when we have an empty list:

  1. If there are no to-do items at all
  2. If there are no to-do items in the current filter mode (e.g., all of the items are outstanding, and the filter mode is set to COMPLETED)

This is going to be confusing to the user — the user might not realize that the reason their list is empty is that all of the relevant to-do items have been removed from the list via the filter.

We should improve this.

First, go into res/values/strings.xml and add a new string resource:

  <string name="msg_empty_filtered">Click the + icon to add a todo item, or change your filter to show other items</string>

(note: this will be shown in the book as split across multiple lines, but you are welcome to have it be all on one line in your project, if you wish)

Next, open res/layout/todo_roster.xml in the IDE. Click on our empty TextView. In the “Layout” section of the “Attributes” pane, give the widget 8dp of margin on all four sides, so it does not run all the way to the edges of the screen:

Android Studio, Showing Margins
Android Studio, Showing Margins

Then, open the “gravity” options:

Android Studio, Showing TextView Gravity Options
Android Studio, Showing TextView Gravity Options

Check the “center” option, which will cause our text to be centered within the space being occupied by the TextView.

Then, in RosterListFragment, update the motor.states observer in onViewCreated() to be:

    viewLifecycleOwner.lifecycleScope.launchWhenStarted {
      motor.states.collect { state ->
        adapter.submitList(state.items)

        binding?.apply {
          loading.visibility = View.GONE

          when {
            state.items.isEmpty() && state.filterMode == FilterMode.ALL -> {
              empty.visibility = View.VISIBLE
              empty.setText(R.string.msg_empty)
            }
            state.items.isEmpty() -> {
              empty.visibility = View.VISIBLE
              empty.setText(R.string.msg_empty_filtered)
            }
            else -> empty.visibility = View.GONE
          }
        }
      }
    }

Here, we use a when block to handle the three cases:

Now, if you run the app, you will see the empty message centered, and you will see the new empty message if you have items but they are all hidden by the filter:

ToDo App, Showing Revised Empty Message
ToDo App, Showing Revised Empty Message

Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.