【问题标题】:How to dynamically store a permanent value to a TextView如何将永久值动态存储到 TextView
【发布时间】:2021-06-04 11:28:53
【问题描述】:

我正在用 Java 制作一个 Android 银行应用程序,这是我遇到问题的提款功能。 Main page

The withdrawal page

当我选择 100 或任何选项时,该值会从余额中扣除,这里的问题是余额是一个 TextView,我正在使用 setText() 更新余额,但是当页面刷新或从一个活动转到另一个活动时不是永久保存,不是动态保存,有什么解决办法?

【问题讨论】:

    标签: java android android-studio textview


    【解决方案1】:

    您可以使用Shared Preferences 永久保存价值
    像这样创建一个 SharedPreference

    SharedPreferences sharedPref = getActivity().getSharedPreferences(
            "amount_key", Context.MODE_PRIVATE);
    

    在您的按钮 onClicks 上写入您的值或以任何方式更改值

    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    //This will put value to sharedpreference with id amount_key
    // like this new value can be 100 less than previous one
    editor.putInt("amount_key", newValueToPutThereInText);
    editor.apply();
    

    这会将newValueToPutThereInText 永久保存到 SharedPreference。

    要访问该值,请使用 this

    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    int amount = sharedPref.getInt("amount_key", anyDefaultValueToUse);
    // and use it in your balance textview
    Textview balance = findViewById(R.id.your_id);
    balance.setText(amount);
    
    

    Here

    【讨论】:

    • lx SharedPreferences类中没有getActivity这样的方法!我们用它做什么?
    • 对于 Context ,不,它不是 Shared Preferences 的一部分,你有什么错误吗??
    猜你喜欢
    • 1970-01-01
    • 2011-01-04
    • 2015-08-24
    • 2022-12-31
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多