Android 如何从 Preference 对象设置和检索数据

Android how to set and retrieve data from Preference object

我正在处理一个偏好片段,一个偏好是select一个外部图像文件作为应用程序背景。

我尝试将文件路径字符串保存到相应的首选项,以便我可以在启动应用程序时从 SharedPreferences 加载该路径数据。

我的问题是当使用 Preference class 而不是 EditTextPreference 时,没有 setText() 方法来保存路径值,我不知道如何将数据存储到 Preference 对象上,然后通过 SharedPreferences.getString("key", "") 在我的 activity.

中检索

如果我改用 EditTextPreference,确实可以,但我必须禁用或自定义 EditTextPreference 的对话框组件,因为我需要启动一个新的 activity 来选择点击此首选项时的图像。

我在官方文档中注意到他们在使用 intent 时使用 Preference。有什么方法可以将数据保存到 Preference 对象,然后在 activity?

中检索该数据
// In preference fragment
private Preference bgPref;
@Override
  public void onActivityResult(
      int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK && data != null) {
      Uri imageUri = data.getData();
      final String path = getFilePath(requireContext(), imageUri);
      if (path != null) {
        bgPref.setText(path); // how to set a string value for a Preference?
        Drawable d = Drawable.createFromPath(path);
        if (containerView != null) {
          containerView.setBackground(d);
        }
      }
    } else {
      Toast.makeText(requireContext(), "You haven't picked Image", Toast.LENGTH_LONG).show();
    }
  }

// In Main activity
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

String bgPath = sharedPrefs.getString("bgPath", "");

Drawable d = Drawable.createFromPath(bgPath);
if (!bgPath.isEmpty()) findViewById(R.id.nav_host_fragment).setBackground(d);
//...

您可以直接编辑此首选项。在 onActivityResult():

@Override
public void onActivityResult(
    int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData();
            final String path = getFilePath(requireContext(), imageUri);
            if (path != null) {
                // Save preference here
                SharedPreferences.Editor editor = sharedPrefs.edit();
                editor.putString("bgPath", path);
                editor.apply();
                // Now recreate activity to refresh the UI
                requireActivity().recreate();
                // In onCreateView, you can use this preference to set background
            }
        } else {
            Toast.makeText(requireContext(), "You haven't picked Image", Toast.LENGTH_LONG).show();
        }
    }
}