I've got a ListView
in my application that's rendered in a ListFragment
's onActivityCreated()
using setListAdapter()
. Passed in to this setListAdapter()
are my implementation of ArrayAdapter
. At some times this adapter can be empty, and that's fine, but at those moments I would like to show a message in the list telling that there are no items, instead of just an empty view. However I don't really know how to achieve this, as for I have researched most people to show lists in a ListActivity
and by doing that you can setEmptyView()
but this doesn't seem doable when using a ListFragment
. Another way of doing this was to change view in the ListFragment
if the ArrayAdapter
has no item's in it, then change view to another showing the message, but this seems to me a bit hacky.
Whats really the proper way of doing what I want to achieve?
Tried to setEmptyView()
to my ListView
but that didn't work either, see code on how views are inflated in my ListFragment
:
public class MyFragment extends ListFragment {
@SuppressLint("InflateParams")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ListView listView = (ListView) inflater.inflate(R.layout.my_list, null);
listView.setEmptyView(inflater.inflate(R.layout.list_items_missing, null));
return listView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MyItemArrayAdapter adapter = new MyItemArrayAdapter(getActivity());
// Populate adapter with items...
setListAdapter(adapter);
}
}
Shouldn't this result in the empty view beeing shown if no items exists in my adapter?
1) Try putting backgroundImage
for ListView
inside xml
. If no item, show backgroundImage
, if there is item, put background color.
2) You can also do what as @kgandroid suggested and here, setEmptyView()
which you set custom view.
Example:
Another: