WSBT
WSBT

Reputation: 36383

Add a different element to ArrayAdapter/ListView

I have a ListView that's being populated by an ArrayAdapter:

someListView.setAdapter(adapter);

Each element in the adapter is inflated using the same layout.xml. Now I want to add an element of a different type (inflated using a different layout file) to the beginning of the ListView.

What I want to achieve is, to have a special element on top of all other elements in the list view, but also scrolls with the list (exits the screen from top if the user scrolls down).

I've tried to add the new element to the array but it's a different type so that won't work.

I've tried to insert a dummy element to the array at position 0, and modify the adapter's getView() so that if (position == 0) return myUniqueView, but that screwed up the entire list view somehow: items not showing, stuff jumping all over the place, huge gaps between elements, etc.

I start to think the best practice of achieving what I want, is not through editing the array adapter. But I don't know how to do it properly.

Upvotes: 1

Views: 464

Answers (3)

Silverstorm
Silverstorm

Reputation: 15845

In your adapter add a check on the position

private static final int LAYOUT_CONFIG_HEADER = 0;
private static final int LAYOUT_CONFIG_ITEMS = 1;   

int layoutType;

@Override
public int getItemViewType(int position) {

    if (position== 0){
        layoutType = LAYOUT_CONFIG_HEADER;
    } else {
        layoutType = LAYOUT_CONFIG_ITEMS;
    }
    return layoutType;
}


@Override  
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutInflater inflater = null;
int layoutType = getItemViewType(position);
   if (row  == null) {
    if (layoutType == LAYOUT_CONFIG_HEADER) {
      //inflate layout header
      }
    }  else {
      //inflate layout of others rows
 }
} 

Upvotes: 0

Ifrit
Ifrit

Reputation: 6821

You don't need anything special to do what you ask. Android already provides that behavior built in to every ListView. Just call:

mListView.addHeaderView(viewToAdd);

That's it.

ListView Headers API
Tutorial

Upvotes: 2

Aparichith
Aparichith

Reputation: 1535

Do't know exactly but it might usefull

https://github.com/chrisjenx/ParallaxScrollView

Upvotes: 0

Related Questions