【问题标题】:How to program Button to change function depending on integer variable in SharedPreferences如何根据 SharedPreferences 中的整数变量对 Button 进行编程以更改功能
【发布时间】:2018-01-14 14:34:07
【问题描述】:

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

我的方法是设置一个“if/else if”循环,该循环编辑一个名为“page”的字符串共享首选项,然后将“page”应用于按钮操作。很明显,我的 if/else if 循环没有编辑“页面”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);
        }
    });
}

【问题讨论】:

    标签: android button sharedpreferences


    【解决方案1】:

    这里你没有更新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);
        }
    

    【讨论】:

    • 好的,谢谢!结果完全正确。我真的很感谢你的时间和帮助一个随机的陌生人问菜鸟问题。对你好!
    猜你喜欢
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 2022-01-11
    • 2021-05-06
    • 2019-11-28
    相关资源
    最近更新 更多