使用共享首选项更改按钮的文本 android studio

问题描述 投票:0回答:2

我正在制作一个带有按钮的简单应用程序。当口袋妖怪被抓住时,我希望文本是“释放”,当没有被抓住时,文本是“抓住!”。单击按钮时,我想将 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
2个回答
1
投票

我想这就是你想要的:

在您的应用程序中,您有一个

EditText
允许用户输入神奇宝贝名称。当用户单击切换捕获按钮时,

  • 如果捕获了神奇宝贝名称(神奇宝贝名称已保存在

    SharePreferences
    中),则从
    SharePreferences
    中删除神奇宝贝名称,并将按钮的文本设置为“释放”。

  • 如果未捕获神奇宝贝名称(神奇宝贝名称尚未保存在

    SharePreferences
    中),则将神奇宝贝名称添加到
    SharePreferences
    中,并将按钮的文本设置为“捕获!”。

解决方案

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!");
    }
}

1
投票

SharedPreferences 是

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

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

再次删除时,您应该给出键,而不是值。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.