【问题标题】:Change of button text Android app更改按钮文本 Android 应用程序
【发布时间】:2015-10-01 11:28:55
【问题描述】:

我的应用中有两个屏幕,屏幕“a”和“b”。屏幕“b”有一个按钮,由布局文件定义。我需要从代码中更改按钮的文本。我设法通过使用 button.setText() 来做到这一点,但是当我将屏幕更改为“a”并返回“b”时,文本被更改回初始状态(更改为在布局失败)。我需要避免这种行为,这意味着我需要在更改屏幕后更改文本。 谢谢!

【问题讨论】:

标签: android button android-activity text


【解决方案1】:

您可以使用共享首选项来保存按钮文本:

开始活动后设置文本(onCreate):

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String buttonText = sharedPref.getString("buttonText");
if (buttonText != null) {
   button.setText(buttonText);
}

保存新文本:

button.setText(newButtonText);
sharedPref.editor.putString("buttonText", newButtonText).commit();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-26
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多