android - 每当 SharedPreference 更改时如何更新 TextView?

标签 android sharedpreferences

我一直在尝试以下方法让 textview 更新对 SharedPreference 所做的任何更改,但我在想出下一步时遇到了困难。任何人? :)

public class CallForwardActivity extends Activity implements
        OnSharedPreferenceChangeListener {

    SharedPreferences userInfo;
    Context context;
    UserController userControl;
    private static final String USERINFO_FILE = "StoredUserInfo";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.callforward);
        context = this;
        userInfo = this.getSharedPreferences(USERINFO_FILE, 0);
        userControl = new UserController(context);
        final TextView setActiveNumberTV = (TextView)
                                        findViewById(R.id.activeNumberTextView);
        setActiveNumberTV.setText(userControl.GetActiveNumber());
        final RelativeLayout showAvailablenumbers = (RelativeLayout)
                                        findViewById(R.id.showAvailableNumbers);
        showAvailablenumbers.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Intent i = new Intent(getParent(),
                        AvailableNumbersActivity.class);
                SettingsActivityGroup parentActivity =
                                            (SettingsActivityGroup) getParent();
                parentActivity.ReplaceView(
                        "Show Available Numbers Activity", i);
            }
        });
    }

    public void onSharedPreferenceChanged(SharedPreferences arg0,
            String arg1) {
        final TextView setActiveNumberTV = (TextView)
                                        findViewById(R.id.activeNumberTextView);
        setActiveNumberTV.setText("...");
    }
}

最佳答案

您没有注册 OnPreferenceChangedListener。在 onCreate 中调用 userInfo.registerOnSharedPreferenceChangeListener(this),它应该可以工作。

关于android - 每当 SharedPreference 更改时如何更新 TextView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9394961/

相关文章:

android - 在不安装新 APK 的情况下更新应用程序

java - 配对的设备未显示在列表中

android - 更新Android应用程序时如何清除旧偏好?

android - SharedPreferences.getAll() 没有为假的首选项键。如何检索所有 key ?

java - 如何将数据存储在一个 fragment 中以将其获取到另一个 fragment 中?

java - 如何在android中选择和取消选择图像?

java - Firebase 数据库规则 parent 跟踪 child

java - Firebase 数据库数据收集

android - ListView 中的切换按钮单击自身

android - GSON 在从共享 prefs 获取时将之前存储的 List 转换为 LinkedTreeMaps 的 ArrayList