Android的 - 如何设置一个preference在code如何设置、Android、code、preference

2023-09-12 07:04:57 作者:错付相思意

我有一个Android应用程序中,我有我的preferences在一个XML文件,它工作正常。现在我想用code,而不是显示整个preference屏幕设置preferences之一,我怎么会去这样做?

I have an Android application in which I have my preferences in a xml file, which works fine. I've now want to set one of the preferences using code instead of displaying the entire preference screen, how would I go about doing this?

推荐答案

我想通过preferences你指的是应用程序的preferences而不是Android手机的设置。

I assume by preferences you are referring to your application's preferences and not Android phone settings.

要保存您的应用程序的运行之间preferences你需要做以下

To store preferences between runs of you application you need to do the following

创建共享preferences反对

Create a SharedPreferences object

SharedPreferences settings = getSharedPreferences(String n, MODE_PRIVATE);

字符串n标识您的preferences,第二个参数是他们将要访问的模式的

实例化一个编辑器对象

SharedPreferences.Editor editor = settings.edit();

注意:不要试图settings.editor.edit(),这不会让一个持久对象和低于code将无法正常工作的

写您的preferences到缓冲区

Write your preferences to the buffer

editor.put...(String, value)

有许多放功能,putString,putBoolean等。字符串是关键(版本,好事办好)和值是值(1.5.2,真)

刷新缓冲区

editor.commit();

这其实是写你把到preferences。如果此行之前,你的应用程序崩溃那么preferences将不会被写入。还有一个记录错误:提交()应该返回一个布尔值指示成功或失败。上次我检查它总是返回false。的

这些preferences将被存储在手机上,并且只可以访问你的应用程序。

These preferences will by stored on the phone and will only be accessible to your application.

更多文档这里