Search code examples
androidtitaniumaddition

Adding number to label on swtichclick in titanium


I am new to the scene and wonder how i am to go about this. I have a switch that should add +1 or a "point" to a label when the switch is true. and When it is false it should withdraw that same "point".

var win = Ti.UI.createWindow({
backgroundColor: 'white'
});

var view = Ti.UI.createView();

var win = Ti.UI.createWindow({
  backgroundColor: 'white'
});

var basicSwitch = Ti.UI.createSwitch({
 title: "+1"
});


basicSwitch.addEventListener('click',function(e){

});

 var label1=Ti.UI.createLabel({
    text: ""

 });


view.add(basicSwitch);
win.add(view);
win.open();

My code so far,not much i know.


Solution

  • Here you go first of all their are following errors in your code

    1)Making window 2 times

    2)Creating a label but not adding to parent container

    3)Switch has change event listener instead of click one

    4)You can set the switch title

    and Here goes the correct code

    var win = Ti.UI.createWindow({
        backgroundColor : 'white'
    });
    var view = Ti.UI.createView({
        width : Ti.UI.FILL,
        height : Ti.UI.FILL
    });
    
    var basicSwitch = Ti.UI.createSwitch({
        top : 30,
        value : false,
    });
    
    basicSwitch.addEventListener('change', function(e) {
        if (e.value = true) {
            label1.text = 1;
        } else {
    
        }
    });
    
    var label1 = Ti.UI.createLabel({
        text : ""
    
    });
    view.add(label1);
    view.add(basicSwitch);
    win.add(view);
    win.open();
    

    Thanks