Tuesday, August 12, 2014

Sencha Touch List Set Dynamic Height

Hello,

Recently in one of my project, there was a requirement to create a list which has items of different height and we have to set height of the list as per number of items. For example one item has height 80 pixel and other two items have height 100 pixel so list height should be set to 280 pixels. In this blog I will explain how to do this.

As we all now list needs a container with fit or card layout so inside that list can be scrollable based on number of items While in our case we have to make complete panel scrollable along with list so we have to list height as per number of items. For that there is one simple way if items height is fixed. For example if item height is 20 pixel and list has 10 items you can set list height to 200 so all the items would be visible. But in case you have variable heights in items you can use following approach. We will loop through each items in the list and get item element client height. Add it together and set list height to sum of all the item heights.

For example we have list with following config

{
      xtype: 'list',
      itemId: 'myList',
      id: 'myList',
      scrollable: false,
      itemHeight: 80,
      store: 'myStore',
      itemTpl: '<div>{longOrShortText}</div>'
}

And we have added reference in controller.

myList : '#myList'

Now in controller when your store is loaded you can add following logic

var totalHeight = 0;
var items = this.getMyList().getViewItems();
var itemsLn = items.length;
for (i = 0; i < itemsLn; i++) {
     item = items[i];
     totalHeight = totalHeight + item.element.dom.clientHeight;
}
this.getMyList().setHeight(totalHeight);

So here we are looping through all the items, find out item client height and add it together and set list height. Hope this helps you.