如何动态地将永久值存储到 TextView
How to dynamically store a permanent value to a TextView
我正在用 Java 制作一个 Android 银行应用程序,这是我遇到问题的提款功能。
Main page
The withdrawal page
当我选择 100 或任何选项时,该值将从余额中扣除 这里的问题是余额是一个 TextView 我正在使用 setText()
来更新余额但是当页面刷新或从activity 到 activity 它不是永久存储的,它不是动态保存的,那么解决方案是什么?
您可以使用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。
并使用此
访问该值
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
我正在用 Java 制作一个 Android 银行应用程序,这是我遇到问题的提款功能。 Main page
The withdrawal page
当我选择 100 或任何选项时,该值将从余额中扣除 这里的问题是余额是一个 TextView 我正在使用 setText()
来更新余额但是当页面刷新或从activity 到 activity 它不是永久存储的,它不是动态保存的,那么解决方案是什么?
您可以使用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。
并使用此
访问该值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