SharedPreference UI控件未更新

时间:2017-10-19 09:59:09

标签: android xml sharedpreferences

我使用SharedPreference存储相机预览的缩放值。 从SharedPreference菜单中,如果我从那里更改缩放值,一切正常。 我还实现了ScaleGestureDetector来设置这个缩放值。

问题是,当使用手势检测器时,当我进入SharedPreference菜单时,它没有更新控件。

SharedPreference(PrefsFile.xml)的实际XML已更新 -

<float name="Zoom Area" value="1.0" />

然而,UI部分(package_preference.xml)的XML文件仍设置为先前的值 -

<string name="pref_zoom_area">0.7</string>

我的听众在片段中 -

public class Camera2VideoFragment extends Fragment implements View.OnClickListener, FragmentCompat.OnRequestPermissionsResultCallback, View.OnTouchListener {

    ...

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor *= detector.getScaleFactor();

            // Don't let the object get too small or too large.
            mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 1.0f));

            return true;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
            mParameters.set_zoom_area(mScaleFactor);
            SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
            SharedPreferences.Editor editor = settings.edit();
            Log.d(TAG, "onScaleEnd() mParameters.get_zoom_area() = " + mParameters.get_zoom_area());
            editor.putFloat(getString(R.string.pref_zoom_area), mParameters.get_zoom_area());
            editor.apply();
        }
    }

    ...
}

我可以确认正在调用onScaleEnd()

我之前有过editor.commit(),但我认为editor.apply()可以解决这个问题但是还没有。

1 个答案:

答案 0 :(得分:0)

所以我现在有这个工作。我已经创建了一种方法来更新首选项值,当显示首选项视图的相应片段在onResume()完全可用时。

@Override
public void onResume() {
    super.onResume();
    getPreferenceScreen().getSharedPreferences()
            .registerOnSharedPreferenceChangeListener(this);
    updatePreferencesUI();
}

public void updatePreferencesUI() {
    ListPreference mListPreference;

    // Some settings may have been changed from outside this fragment. Even though the
    // SharedPreference itself may be updated, the UI controls for this fragment will need
    // updating separately, otherwise the two groups would be out of sync.
    CameraActivity cameraActivity = (CameraActivity) getActivity();

    mListPreference = (ListPreference) findPreference("pref_zoom_area");
    mListPreference.setValue(String.valueOf(cameraActivity.mParameters.get_zoom_area()));

}