(转)Android SharedPreferences的使用
原文連接:http://blog.csdn.net/shang_515/article/details/6884635
?
SharedPreferences是Android平臺(tái)上一個(gè)輕量級(jí)的存儲(chǔ)類,主要是保存一些常用的配置比如窗口狀態(tài),一般在Activity中 重載窗口狀態(tài)onSaveInstanceState保存一般使用SharedPreferences完成,它提供了Android平臺(tái)常規(guī)的Long長(zhǎng) 整形、Int整形、String字符串型的保存,它是什么樣的處理方式呢?SharedPreferences類似過去Windows系統(tǒng)上的ini配置文件,但是它分為多種權(quán)限,可以全局共享訪問,android123提示最 終是以xml方式來保存,整體效率來看不是特別的高,對(duì)于常規(guī)的輕量級(jí)而言比SQLite要好不少,如果真的存儲(chǔ)量不大可以考慮自己定義文件格式。xml 處理時(shí)Dalvik會(huì)通過自帶底層的本地XML Parser解析,比如XMLpull方式,這樣對(duì)于內(nèi)存資源占用比較好。
?
這種方式應(yīng)該是用起來最簡(jiǎn)單的Android讀寫外部數(shù)據(jù)的方法了。他的用法基本上和 J2SE(java.util.prefs.Preferences)中的用法一樣,以一種簡(jiǎn)單、 透明的方式來保存一些用戶個(gè)性化設(shè)置的字體、顏色、位置等參數(shù)信息。一般的應(yīng)用程序都會(huì)提供“設(shè)置”或者“首選項(xiàng)”的這樣的界面,那么這些設(shè)置最后就可以 通過Preferences來保存,而程序員不需要知道它到底以什么形式保存的,保存在了什么地方。當(dāng)然,如果你愿意保存其他的東西,也沒有什么限制。只 是在性能上不知道會(huì)有什么問題。
在Android系統(tǒng)中,這些信息以XML文件的形式保存在?/data/data/PACKAGE_NAME?/shared_prefs?目錄下。
?
下面是程序代碼:
?
[java]?view plaincopy
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
通過名稱,得到一個(gè)SharedPreferences,顧名思義,這個(gè)Preferences是共享的,共享的范圍據(jù)現(xiàn)在同一個(gè)Package中,這里 面說所的Package和Java里面的那個(gè)Package不同,貌似這里面的Package是指在AndroidManifest.xml文件中的
?
?
[html]?view plaincopy
布局文件如下:
?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText android:layout_width="185dp" android:id="@+id/user"
android:layout_height="40dp" android:hint="請(qǐng)輸入用戶名"
android:singleLine="true" android:layout_alignParentTop="true"
android:layout_alignLeft="@+id/pass" android:layout_marginTop="66dp">
<requestFocus></requestFocus>
</EditText>
<EditText android:inputType="textPassword"
android:layout_width="185dp" android:id="@+id/pass"
android:layout_height="40dp" android:hint="請(qǐng)輸入密碼" android:singleLine="true"
android:layout_below="@+id/user" android:layout_centerHorizontal="true"
android:layout_marginTop="44dp">
</EditText>
<ImageButton android:layout_height="40dp"
android:layout_width="80dp" android:id="@+id/loginButton"
android:background="@drawable/dengluxitong"
android:layout_centerVertical="true" android:layout_alignRight="@+id/pass"
android:layout_marginRight="17dp"></ImageButton>
</RelativeLayout>
運(yùn)行結(jié)果如下,首次顯示的時(shí)空白,第二次運(yùn)行時(shí)如下:
轉(zhuǎn)載于:https://www.cnblogs.com/lovers/articles/2679853.html
總結(jié)
以上是生活随笔為你收集整理的(转)Android SharedPreferences的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 图像二值形态学——腐蚀和膨胀的C语言实现
- 下一篇: 买重疾险的8大误区分析