Search code examples
androidtitaniumtitanium-mobile

display content in tableview having exactly two columns in Titanium


I have a json response which has images and other content of which I want to show images in tableview but it should consists of only two columns with unlimited rows.

Can anyone help on this query?

Code:

for (var i = 0; i < jsonResponse.length; i++) 
{ 
    var row = Ti.UI.createTableViewRow({ 
        width : Ti.UI.SIZE, 
        height : Ti.UI.SIZE, 
        layout: "horizontal" 
    });

    var myImage = Ti.UI.createImageView({ 
        width : Ti.UI.SIZE, 
        height : Ti.UI.SIZE, 
        image : jsonResponse[i].cover_image_url 
    }); 

    row.add(myImage); 
    data.push(row); 
} 
table.setData(data); 
win2.add(tableview);

Solution

  • Something like this should do:

    var rowHeight = 50; // just pick the right height here
    var imageRowIsFull = false;
    var row = Ti.UI.createTableViewRow({ 
            width : '100%', 
            height : rowHeight, 
            layout: "horizontal" 
        });
    for (var i = 0; i < jsonResponse.length; i++) 
    { 
        var myImage = Ti.UI.createImageView({ 
            width : '50%', 
            height : rowHeight, 
            image : jsonResponse[i].cover_image_url 
        }); 
    
        myImage.addEventListener('click', function(event){
              //event handling here
        });
    
        row.add(myImage); 
        imageRowIsFull = false;
    
        if ( (i + 1) % 2 == 0) { //this will add a new row every 2 items.
           imageRowIsFull = true; 
           data.push(row); 
           row = Ti.UI.createTableViewRow({ 
                width : '100%', 
                height : rowHeight, 
                layout: "horizontal" 
           });
        }
    } 
    
    if (!imageRowIsFull) { //do not forget to add the last row
           data.push(row); 
    }
    table.setData(data); 
    win2.add(tableview);