ListView.itemTemplate and Images in NativeScript

7.6k views Asked by At

I am trying to build a Contacts List type POC for NativeScript. And I would like to have an image and name in a list item. The code that I am using for the layout is as follows

<Page loaded="pageLoaded">
    <ListView items="{{ myItems }}">
        <ListView.itemTemplate>
            <Image src="{{ imageSrc }}" />
            <Label text="{{ title }}" />
        </ListView.itemTemplate>
    </ListView>
</Page>

Apparently, the title value is coming up fine, but the image is not showing up at all. When I try to put the same Image code in an empty page, NativeScript builds the page with image.

Can anyone tell me why the image is not coming up in the listview template? And how can it be displayed?

Thanks

1

There are 1 answers

2
Nathanael On BEST ANSWER

I tested this; You need to put the inner items in a layout. I believe the itemTemplate can only be ONE child. All my tests seem to indicate that itemTemplate points to a single child.

So this works fine as the single child is a StackLayout which then contains your two items.

XML:

<Page xmlns="http://www.nativescript.org/tns.xsd" loaded="onPageLoaded">
        <ListView id="listview" items="{{ myItems }}">
            <ListView.itemTemplate>
                <StackLayout orientation="horizontal">
                <Label text="{{ title }}" />
                <Image src="{{ src }}" stretch="none" />
                </StackLayout>
            </ListView.itemTemplate>
        </ListView>
</Page>

For code completion (for anyone looking at this in the future) the simplest JS:

var observableArray = require("data/observable-array");
function onPageLoaded(args) {
  var page = args.object;
  var array = new observableArray.ObservableArray();

  array.push({title: "Title1", src: 'http://master-technology.com/images/Logo1.gif')});
  array.push({title: "Title2", src: 'http://master-technology.com/images/demos/Apps-TurnItOffLogo.gif')});

  page.bindingContext = {myItems: array};
}
exports.onPageLoaded = onPageLoaded;