Best practices combining list and non-list views,

2019-05-11 20:33发布

问题:

I'm trying to tackle a problem that seemingly many Android developers have, which is how to intersperse lists with non-list data, in one big scrollable pane.

The model I have in mind is the screen for an individual app in the Market. You have a big description, a list of a few lazily loaded comments, and then some individual items that do different things, like visit the developer's web page, call them, etc. And then in between them all, are nice section headers.

Emulating this approach seems to be extremely hard. I've read enough SO answers and mailing list posts to know not to put a ListView inside of a ScrollView, but I want the same effect without using addHeader() and addFooter() with very complex header and footer views.

I've tried using a LinearLayout that I stock with views myself, but I can't get the pleasant click effects that default list items have (the orange background, white for long-click, etc.).

What do I do?

回答1:

Take a look at my MergeAdapter, which is designed to handle scenarios like this.



回答2:

Why not use a header? It's easy. Define the header contents in a separate layout. Your activity layout contains nothing but the ListView that you want at the bottom. No scroll view!

Then call

View headerView = getLayoutInflater().inflate(R.layout.header_layout, null);
ListView listView = (ListView) findViewById(R.id.my_list_view);
listView.addHeaderView(headerView, null, false);   

It's crucial to call that form of addHeaderView so that the header is disabled. Otherwise, it can be selected, which looks totally weird.



回答3:

Mark's example would work. basically you need an adapter with different view types. Another nice example is http://jsharkey.org/blog/2008/08/18/separating-lists-with-headers-in-android-09/ which might work better than Mark's because you want to have separators and group things together.