Android ListView custom header

2019-07-17 08:06发布

问题:

I have a custom listview, which is re-arrangeable(drag & drop) and obviously scrollable. I need to add a custom header with this listview which should scroll with the list.

I have tried "listView.addHeaderView(header)" with a custom header layout. But header becomes messed up during list re-arrangement. So I don't want to use addHeaderView(...).

I have also tried to put my activity layout which is a LinearLayout, inside a ScrollView and expand the list as suggested here - How can I put a ListView into a ScrollView without it collapsing?. But, scrolling seems slow and ScrollView is creating issue in list item re-arrangement.

So is there any other way to accomplish this effect? I would prefer some solution in layout.

I am fairly inexperienced in Android UI. Thanks in advance.

回答1:

You can add a Header View to your list, using the following code,

View header = getLayoutInflater().inflate(R.layout.header, null); 
ListView listView = getListView();  
listView.addHeaderView(header);  
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice,android.R.id.text1, names)); 

But for this, you need to define layour for the Header View, check this Link Android ListActivity with a header or footer

Edit- As per comment, I would like to mention that, It is not a good practice to use a ListView inside a ScrollView. The best possible solution, I found so far is to add HeaderView to your ListView. It would be better if the OP could mention, what problems he is facing with the HeaderView

If you want a scrollable header, you should definitely go with the HeaderView. But if you want to have a static header above the ListView, you could use a TextView as a Heading of the ListView.



回答2:

you can add static header in layout I mean the layout where you have scrollview above that add a linear layout for static header go through this question it will help you



回答3:

If you don't want that your list having a horizontal scrollview so you can create a Xml layout with horizontal linear layout(same as your list Layout) then include it at the top of your listview layout but if you want it horizontally srcollable so you have two choice : one is what you mention as addheader view and second is a Custom ScrollView which you can find a good solution here