【发布时间】:2021-08-27 04:04:18
【问题描述】:
我正在研究一个偏好片段,其中一个偏好是选择一个外部图像文件作为应用背景。
我尝试将文件路径字符串保存到相应的首选项,以便在启动应用程序时从SharedPreferences 加载该路径数据。
我的问题是当使用Preference 类而不是EditTextPreference 时,没有setText() 方法来保存路径值,我不知道如何将数据存储到Preference 对象然后检索在我的活动中通过SharedPreferences.getString("key", "")。
如果我改用EditTextPreference,它确实可以工作,但我必须禁用或自定义EditTextPreference 的对话框组件,因为在点击此首选项时我需要启动一个新活动来选择图像。
我在官方文档中注意到他们在一起使用意图时使用Preference。有没有办法将数据保存到Preference 对象,然后在活动中检索该数据?
// 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);
//...
【问题讨论】:
-
你试过这个 -> github.com/skydoves/PreferenceRoom
-
I cannot figure out how to store the data onto a Preference object and then retrieve through SharedPreferences.getString("key", "")??如果您以后想从共享首选项中检索数据,则应将数据保存到共享首选项中。 -
感谢您的回复,我理解您的意思,确实它正在使用我的片段文件中的此代码,我只是想知道是否有与
setText的EditTextPreference类似的东西。PreferenceManager.getDefaultSharedPreferences(requireContext()) .edit() .putString("bgPath", path) .apply(); -
如果您希望路径字符串在您的首选项下方可见,您只需将您选择的路径设置为该首选项的摘要。
标签: java android sharedpreferences