导航离开后我如何在页面上保留更改

时间:2016-10-26 17:30:02

标签: nativescript

我有这个页面有两个按钮,如下所示。目标是触发一个改变按钮ontap颜色的事件。

问题是,在点击事件改变了颜色并且我离开它之后,按钮的颜色返回到默认值。

请问我如何在导航后保留更改?

<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="pageLoaded" navigatedTo="navigatedTo">

<ActionBar title="Settings">
  <NavigationButton text="Back" android.systemIcon="ic_menu_back" tap="homeTap"/>
</ActionBar>
<StackLayout orientation="vertical">

    <Button class="optionOne" text="option one" tap="optionOneTap"> </Button>
    <Button class="optiontwo" text="option two" tap="optionTwoTap"> </Button>  


</StackLayout>
</Page>

javascript代码:

var orientation = require('nativescript-orientation');
var page = require("ui/page");
var button = require("ui/button");

exports.pageLoaded = function (args) {
    page = args.object;
}


exports.navigatedTo = function () {
    orientation.setOrientation("portrait");
}   


exports.optionOneTap = function () {
    page.addCss(".optionOneTap {background-color: red}")
}  

exports.optionTwoTap = function () {
    page.addCss(".optionTwoTap {background-color: blue}")
}

2 个答案:

答案 0 :(得分:1)

您可以使用静态类来保持状态;

之类的东西
export class AppState {
    static state = {
          //some properties
    };
}

或者使用此插件:http://docs.nativescript.org/cookbook/application-settings

var appSettings = require("application-settings");

appSettings.setString("lastColor", "blue");
var stringValue = appSettings.getString("lastColor");

答案 1 :(得分:0)

所以我解决了这个问题。需要完成的是......保存按下按钮的状态,以便用户可以知道导航回页面并能够知道他之前按下或输入的内容。

当用户按下任何按钮时执行操作:

exports.optionOneTap = function () {
    //save the number to app settings, u will use this later
    applicationSettings.setNumber("numberSaved", 1);
    page.addCss(".optionOneTap {background-color: red}")

} 

exports.optionTwoTap = function () {
    //save number again, u sill need  it later
    applicationSettings.setNumber("numberSaved", 2);
    page.addCss(".optionTwoTap {background-color: blue}")
}

现在创建一个私有函数:

function getButtonColorState () { //name it whatever you want
    var buttonPressed = applicationSettings.getNumber("numberSaved"); 
    if (buttonPressed === 1) {
        page.addCss(".optionOneTap {background-color: red}")
    }
    else if (buttonPressed === 2) {
        page.addCss(".optionTwoTap {background-color: blue}")
    }
}

最后,在页面加载或导航到页面时调用此函数。

exports.pageLoaded = function (args) {
    page = args.object;
    getButtonColorState();
}

完成!