且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android - 如何在代码中设置首选项

更新时间:2023-11-26 13:49:10

我假设根据偏好,您指的是应用程序的偏好,而不是 Android 手机设置.

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

要在应用程序运行之间存储首选项,您需要执行以下操作

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

  1. 创建一个 SharedPreferences 对象

  1. Create a SharedPreferences object

SharedPreferences settings = getSharedPreferences(String n, MODE_PRIVATE);

字符串 n 标识您的首选项,第二个参数是它们将被访问的模式

实例化编辑器对象

SharedPreferences.Editor editor = settings.edit();

注意:不要尝试settings.editor.edit(),这不会创建一个持久化对象,下面的代码也不起作用

将您的首选项写入缓冲区

Write your preferences to the buffer

editor.put...(String, value)

put函数有很多,putString,putBoolean等,String是key(version",good run"),value是值(1.5.2",true)

刷新缓冲区

editor.commit();

这实际上写入了您的首选项.如果您的应用程序在此行之前崩溃,则不会写入首选项.还有一个记录的错误:commit() 应该返回一个指示成功或失败的布尔值.最后我检查它总是返回 false.

这些首选项将存储在手机上,并且只能由您的应用程序访问.

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

更多文档在这里