9

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

Shhhhh
  • 188
  • 2
  • 11

1 Answers1

16

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;
Nathanael
  • 5,369
  • 18
  • 23
  • Your solutions worked perfectly. Thanks!! I still dont understand the requirement of ObservableArray() here. – Shhhhh Jun 08 '15 at 21:28
  • 1
    The only purpose for the ObservableArray is so that you can make changes live and it will do updates. It is recommended when you do any binding that you use Observable so that it can be two way changed. But you can just use a plain array if you want if the list is not going to be updated frequently. – Nathanael Jun 08 '15 at 22:24
  • I see. That makes sense. – Shhhhh Jun 09 '15 at 13:49