Android的 - 如何设置一个preference在code [英] Android - How Do I Set A Preference In Code

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

问题描述

我有一个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

  1. 创建共享preferences反对

  1. 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.

更多文档这里

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

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