Ahzam Ahmad
Ahzam Ahmad

Reputation: 35

ListView with specific spacing between items

I have a ListView and wish to have spacing between items increase/decrease depending on the two items. I basically have items alternate sides randomly and want the spacing to increase when the items are on opposite sides. I know how to increase the spacing between all items equally but am at a loss when it comes to specific rows.

Upvotes: 1

Views: 224

Answers (1)

earthw0rmjim
earthw0rmjim

Reputation: 19417

Simply compare the data of the corresponding list rows and add an appropriate margin or padding to the View.

Just an example (kinda hard to give specific help without seeing any of your code):

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(someContext)
    View row = inflater.inflate(R.layout.some_layout, parent, false);

    if (position > 0) {
        Data previous = someDataset.get(position - 1);
        Data current = someDataset.get(position);

        if (previous.something() == current.something()) {
            // add margin or padding to row
        }
    }

    // set TextView texts, ImageView images etc., whatever your row has

    return row;
}

If you don't know how to add margin to a View programmatically, there are many existing questions for that, here's an answer.

If you would rather add padding, just call the setPadding() method on your View.

Upvotes: 2

Related Questions