views:

54

answers:

4

I have a listview that is the main part of my activity. When there are no objects in the listview, I want to replace it with a helpful message (a TextView). I simply call setContentView again if the list is unpopulated in onResume.

However, this only works for the TextView. If I call setContentView(R.layout.mylayout), then I get a blank. This is especially bothersome after the user has created an item that would properly go into the listview in another activity and returns.

Do I have the right approach? How do I fix this?

Thanks!

+1  A: 

Well, what do you have in your listview? If you only have text then you can input your message as the first part of the listview unless something is added. Like if you have an array of strings being printed with the listview, try having the first of the array being your message unless someone adds something else.

Enigma Development
I suppose that is a possible solution, but what would I do in a more complicated situation, where I wanted to anchor something more substantial in place?
SapphireSun
+1  A: 

Instead of using setContentView maybe you could try changing the visibility flags of each View using setVisibility. If the list isn't populated, you can change it's visibility to View.GONE, and make the helper TextView visible with View.VISIBLE, and do the opposite if the ListView is populated. Not sure if this is exactly what you're looking for, but it is worth a shot.

BenV
+1  A: 

I'd have added this to BenV's answer as a comment, but I can't paste in code. Here's how I do the layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <ListView android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1.0"
  />
  <TextView android:id="@android:id/empty"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:gravity="center"
         android:text="@string/list_empty"
  />
</LinearLayout>

Just before calling notifyDataSetChanged() on the ArrayAdapter, I do a setVisibility(View.VISIBLE) and setVisibility(View.GONE) on list and empty respectively if there are items in the list and the reverse if the list is empty.

Blrfl
+3  A: 

The ListView has a method called setEmptyView(View) through which you can display any view when the list is empty. The ListView takes care of hiding/displaying the view.

TextView emptyView = (TextView)findViewById(R.id.empty_list_view);
placesList.setEmptyView(emptyView);

The layout code is the same as Blrfl's code.

Abhinav