简体   繁体   中英

Android Back Button Handling In Appcelerator

I want to integrate an android back button functionality in appcelerator for a parent window and its subsequent child views. I have just a single window in the entire project. Other screens are the children of this parent window. Any suggestions?

There are 2 cases you might be interested in:

  1. Over-ride the default behaviour of the back button press.

    $.window.onBack = function () { // run your code like change views or whatever you like };

    • Use Window's onBack property to attach back button callback.
    • It will have you take control of what should happen when back button is pressed on that window.
  2. If you just want to listen to back button press along with default behaviour of back button press, use Window's androidback event .

    $.window.addEventListener('androidback', function (e){});

    • Note that this method will still close the window you are on, but will allow you to run some code on back button press.

I believe you are looking for method 1.

Note: Method 1 is only available after or > SDK 5.5.1.GA. It was a breaking change in 6.0.0.GA. So do read docs properly & put some tests on their functionality.

Added Code sample to simulate back button feature.

Alloy.Globals.trackingArray = [];

function addNewView(_controllerName, _args) {
    var newView = Alloy.createController(_controllerName, _args).getView();
    $.window.add(newView);

    // add new view in tracking array.
    Alloy.Globals.trackingArray.push(_controllerName);
}

// now use something like this whenever you remove any view using backpress
function onBackPress() {
    // remove lastly added view
    Alloy.Globals.trackingArray.pop(_controllerName);

    // add last opened view to simulate back button feature
    var lastAddedView = Alloy.Globals.trackingArray[Alloy.Globals.trackingArray.length - 1];

    var tempView = Alloy.createController(lastAddedView).getView();

    $.window.add(tempView);
}

This is the basis of how you can manage this feature. But do note a point here that you will need to take care of managing arguments passed to while creating a new view or controller. There are multiple ways to do it & it depends on your coding style. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM