Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

android - Display "No Item" message in ListView

I've created some composie UIs in my android apps and there are some ListView controls -among other controls- inside a view. Because of this, I have used "Activity" as my activity base class.

Now I need to display a simple message like "No Item" when the ListView that is bound to my adapter is empty. I know this is possible when using ListActivity but I'm not sure what's the best approach for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can have an empty view without a ListActivity! The correct method is as follows

First add an 'empty view' to your layout XML below your list

...
<ListView 
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />

<TextView
    android:id="@+id/empty"
    android:text="Empty"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    />
...

Next override the onContentChanged method of your activity and set the empty view of your list to your empty view:

@Override
public void onContentChanged() {
    super.onContentChanged();

    View empty = findViewById(R.id.empty);
    ListView list = (ListView) findViewById(R.id.list);
    list.setEmptyView(empty);
}

That's it! Android will take care of hiding/showing the list and empty view when you update the adapter.

The Magic

Deciding whether the empty view is shown or not is handled by the superclass of ListView, AdapterView. AdapterView registers a DataSetObserver on the set adapter so it is notified whenever the data is changed. This triggers a call to checkFocus in AdapterView which contains the following lines

if (mEmptyView != null) {
    updateEmptyStatus((adapter == null) || adapter.isEmpty());
}

and sets the empty view visibility based on whether the adapter is empty or not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...