Nativescript-Segmented-Bar-with-Colour-Change


#1

Here is an example of how to implement a colour change depending on the selected index of a Segmented Bar.

<SegmentedBar row="4" loaded="sbLoaded" selectedIndex="sbSelectedIndex" class="segButton" id="segbuttonid" marginTop="20px" height="40">
									<SegmentedBar.items>
										<SegmentedBarItem title="1" />
										<SegmentedBarItem title="2" />
										<SegmentedBarItem title="3" />
										<SegmentedBarItem title="4" />
									</SegmentedBar.items>
								</SegmentedBar>

The Javascript as follows:-

function sbLoaded(args) {
    // handle selected index change
    const segmentedBarComponent = args.object;
    segmentedBarComponent.on("selectedIndexChange", (sbargs) => {
        const page = sbargs.object.page;
        const vm = page.bindingContext;
        const selectedIndex = sbargs.object.selectedIndex;
        switch (selectedIndex) {
            case 0:
                segmentedBarComponent.className = "seg1";
                break;
            case 1:
                segmentedBarComponent.className = "seg2";
                break;
            case 2:
                segmentedBarComponent.className = "seg3";
                break;
            case 3:
                segmentedBarComponent.className = "seg4";
                break;
            default:
                break;
        }
    });
}
exports.sbLoaded = sbLoaded;

And the CSS here:-

.segButton{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    selected-background-color: red;
}
.seg1{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    selected-background-color: red;
}
.seg2{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    selected-background-color: orange;
}
.seg3{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    selected-background-color: green;
}
.seg4{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    selected-background-color: white;
}