我有一个 Android 应用程序,它是一个简单的主屏幕。我想要的是创建一个选项,用户可以自己选择背景。目前我已经做出了该选项,但在我重新启动或按后退按钮后它不会保留背景。它返回到我在 xml 文件中设置为 android:background 的背景。还有出路吗?我听说通过使用共享偏好是可能的。但不知道该怎么做。任何人都可以帮忙解决这个问题吗?
最佳答案
假设您有多个背景可供他们选择,并且他们选择了一个,而您只想存储他们选择的背景的 ID,您将执行以下操作:
SharedPreference sp = getSharedPreferences("uniqueString", 0);
Editor editor = sp.edit();
editor.putInt("userBG", 5);// this is assuming the user picked your 5th bg
editor.commit();
然后在您的 Activity 中的 onCreate 中,您可以再次加载 SharedPreference 并...
int userPic = sp.getInt("userBG", 0); //this will either pull a previously saved number or return 0 (or whatever number you choose to provide as the default there.
就是这样。 这是来自谷歌的示例,以防我的代码 fragment 不够...... http://developer.android.com/guide/topics/data/data-storage.html
请注意,如果您存储的是 int,则可以存储背景本身的可绘制 id,这样可以节省一步转换。然后,您可以将资源直接拉到父布局的背景中。
关于java - 如何在android中自己的应用程序中进行用户可选择的背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8739339/