如何编程Button以根据SharedPreferences

时间:2018-01-14 14:34:08

标签: android button sharedpreferences

我正在编写一个简单的游戏来学习编程。最后,我希望最终按钮根据“得分”转到不同的结尾,“得分”是保存在sharedpref中的整数变量。

我的方法是设置一个“if / else if”循环来编辑一个名为“page”的字符串共享pref,然后将“page”应用于按钮操作。很明显,我的if / else if循环不是编辑“page”sharedpref,因为按钮一直使用先前的值。

这是我对代码的尝试;谢谢你的帮助!

public Button button;


public void init() {

    button=findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {

        SharedPreferences pref = getSharedPreferences("ScorePref", MODE_PRIVATE);
        int score = pref.getInt("Score", 0); 
        //these two lines recall the "score" integer

        SharedPreferences saveGame = getSharedPreferences("PrefFile", Context.MODE_PRIVATE);
        String page = saveGame.getString
                ("page", "com.twigofknowledge.variablebuttonpractice.MainActivity");
        //and then the two above here recall the "page" string sharedpref

        SharedPreferences.Editor editor = saveGame.edit();
        //this is the editor that will change the sharedpref

        @Override

        public void onClick(View v) {

            if (score >= 150) {
                editor.putString("page", "com.twigofknowledge.variablebuttonpractice.page6");
                editor.apply();

            } else if (score <= 150) {
                SharedPreferences.Editor editor = saveGame.edit();
                editor.putString("page", "com.twigofknowledge.variablebuttonpractice.page5");
                editor.apply();

            }
            Intent gotopage = new Intent();
            gotopage.setClassName("com.twigofknowledge.variablebuttonpractice", page);
            startActivity(gotopage);
        }
    });
}

1 个答案:

答案 0 :(得分:0)

此处您没有更新page变量,请更改为以下代码 @override

    public void onClick(View v) {

        if (score >= 150) {
            page = "com.twigofknowledge.variablebuttonpractice.page6";
            editor.putString("page", "com.twigofknowledge.variablebuttonpractice.page6");
            editor.apply();

        } else if (score <= 150) {
            page = "com.twigofknowledge.variablebuttonpractice.page5";
            SharedPreferences.Editor editor = saveGame.edit();
            editor.putString("page", "com.twigofknowledge.variablebuttonpractice.page5");
            editor.apply();

        }
        Intent gotopage = new Intent();
        gotopage.setClassName("com.twigofknowledge.variablebuttonpractice", page);
        startActivity(gotopage);
    }