Search code examples
blackberry-10screen-orientationblackberry-cascades

Handling display orientation on startup


I'll start with an example

ImageButton {
    defaultImageSource: "asset:///images/test_p.png"
    pressedImageSource: "asset:///images/test_p_pressed.png"

    attachedObjects: [ 
        OrientationHandler { //gives "orientation"
            onOrientationAboutToChange: {
                if (orientation == UIOrientation.Landscape) {
                    defaultImageSource = "asset:///images/test_l.png"
                    pressedImageSource = "asset:///images/test_l_pressed.png"
                } else {
                    defaultImageSource = "asset:///images/test_p.png"
                    pressedImageSource = "asset:///images/test_p_pressed.png"
                } 
            }
        }
    ]  
}

Screen rotation works just fine, when it's landscape it uses _l, when it's portrait it uses _p image. The problem is, when I start app in landscape, it will show _p, not _l image (because it's default). How do I check orientation in onCreationCompleted?


Solution

  • I figured it out, it's an obvious one really. You put id to your OrientationHandler, and then you use it in onCreationCompleted.

    ImageButton {
        defaultImageSource: "asset:///images/test_p.png" //do I still need this?
        pressedImageSource: "asset:///images/test_p_pressed.png"
    
        attachedObjects: [ 
            OrientationHandler { //gives "orientation"
            id: orientationHandler //make id so you can call it
                onOrientationAboutToChange: {
                    changeImages(orientation);
                }
            }
        ]  
        function changeImages(orientation){
            if (orientation == UIOrientation.Landscape) {
                defaultImageSource = "asset:///images/test_l.png"
                pressedImageSource = "asset:///images/test_l_pressed.png"
            } else {
                defaultImageSource = "asset:///images/test_p.png"
                pressedImageSource = "asset:///images/test_p_pressed.png"
            } 
        }
        onCreationCompleted: {
            changeImages(orientationHandler.orientation); //call it here
        }
    }