Darrell Brogdon
Darrell Brogdon

Reputation: 6973

How to change the background color of a StackLayout container in NativeScript?

I have the following view XML:

<ListView items="{{ lists }}" itemTap="itemTapped">
    <ListView.itemTemplate>
         <StackLayout class="list-group-item" orientation="horizontal">
            <Label text="{{ name }}" class="item-name" horizontalAlignment="center" />
         </StackLayout>
    </ListView.itemTemplate>
</ListView>

And in itemTapped I want to change the background color of the StackLayout container.

exports.itemTapped = function (args) {
    console.log(args.object.backgroundColor)
    args.object.backgroundColor = 'red'
    console.log(args.object.backgroundColor) 
}

When I run the app and click a list item I see this in the console:

CONSOLE LOG file:///app/pick/pick-page.js:111:14: undefined
CONSOLE LOG file:///app/pick/pick-page.js:113:14: #FF0000
CONSOLE LOG file:///app/pick/pick-page.js:111:14: undefined
CONSOLE LOG file:///app/pick/pick-page.js:113:14: #FF0000

I also tried args.object.className = 'selected-item' that sets background-color: red; in CSS but that didn't work either.

How do I go about dynamically changing that color? Or, is there a better way of indicating that a ListView item was tapped?

Upvotes: 0

Views: 718

Answers (1)

Manoj
Manoj

Reputation: 21908

You are not suppose to directly modify a ListItem from ListView as the elements may be reused as you scroll up / down. You should have an attribute on your data item and toggle that, based on the attribute you may bind the background color on ListItem.

 <ListView items="{{ countries }}" itemTap="{{ onItemTap }}">
    <ListView.itemTemplate>
        <FlexboxLayout flexDirection="row"
            backgroundColor="{{ selected, selected ? 'red' : 'white' }}">
            <Image src="{{ imageSrc }}" class="thumb img-circle" />
            <Label text="{{ name }}" class="t-12"
                verticalAlignment="center" style="width: 60%" />
        </FlexboxLayout>
    </ListView.itemTemplate>
</ListView>

Playground Sample

Upvotes: 1

Related Questions