【问题标题】:CHANGING the text of a button with SHARED PREFERENCES android studio使用 SHARED PREFERENCES android studio 更改按钮的文本
【发布时间】:2021-03-24 12:40:44
【问题描述】:

我正在制作一个带有按钮的简单应用。当一个口袋妖怪被抓到时,我希望文本是“释放”,如果不是,是“抓到!”。单击按钮时,我想将 catch 从 true 更改为 false,反之亦然。

目前,我已经完成了这个(它没有像我预期的那样工作):

    public void toggleCatch(View view) {

        boolean caught;

        String name = nameTextView.getText().toString();

        SharedPreferences captured = getSharedPreferences("pokemon_name",Context.MODE_PRIVATE);

        if (captured.contains (name) ){
            catch_button.setText("Release");
            caught=true;
        }
        else{
            catch_button.setText("Catch!");
            caught=false;
        }

        if (caught) {
            getPreferences(Context.MODE_PRIVATE).edit().putString("pokemon_name", name).commit();
        } else {
            getPreferences(Context.MODE_PRIVATE).edit().remove(name).commit();
        }

    }

如果有人可以帮助我,我将非常感激!

我迷路了,所以我不知道我是否走在正确的道路上,我的代码可能完全错误。

【问题讨论】:

    标签: java android sharedpreferences android-button cs50


    【解决方案1】:

    SharedPreferences 是key-value 对的映射。因此,如果您尝试访问该值,则应检查密钥是否存在,在您的情况下为 pokemon_name

    if (captured.contains("pokemon_name")){
        ...
    }
    

    当再次删除时,您应该提供密钥,而不是值。

    ...edit().remove("pokemon_name").commit();
    

    阅读SharedPreferences官方文档以更好地理解。

    【讨论】:

      【解决方案2】:

      我想这就是你想要的:

      在您的应用程序中,您有一个EditText,允许用户输入口袋妖怪名称。当用户点击切换捕捉按钮时,

      • 如果pokemon名字被捕获(pokemon名字已经保存在SharePreferences中),那么将pokemon名字从SharePreferences中删除,并将按钮的文字设置为“释放”。

      • 如果口袋妖怪名字没有被捕获(口袋妖怪名字还没有被保存在SharePreferences中),那么将口袋妖怪名字添加到SharePreferences并且设置按钮的文本为“Catch!”。

      解决方案

      public void toggleCatch(View view) {
          String name = nameTextView.getText().toString().trim();
          SharedPreferences captured = getSharedPreferences("pokemon_name", Context.MODE_PRIVATE);
          boolean caught = captured.contains(name);
          if (caught) {
              captured.edit().remove(name).apply();
              catch_button.setText("Release");
          } else {
              captured.edit().putBoolean(name, true).apply();
              catch_button.setText("Catch!");
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-05
        • 1970-01-01
        • 2012-11-21
        • 2019-08-27
        • 1970-01-01
        • 2022-01-12
        • 2023-03-17
        • 2021-06-23
        相关资源
        最近更新 更多