Android - 如何在代码中设置首选项 [英] Android - How Do I Set A Preference In Code

查看:36
本文介绍了Android - 如何在代码中设置首选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Android 应用程序,其中我在 XML 文件中有我的首选项,它运行良好.我现在想使用代码设置其中一个首选项,而不是显示整个首选项屏幕,我该怎么做?

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

推荐答案

我假设根据偏好,您指的是应用程序的偏好,而不是 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.

更多文档在这里

这篇关于Android - 如何在代码中设置首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆