有點類似在C++開啟一個檔案來儲存資料。
我們來舉個記錄當下日期時間的例子:
MainActivity.java
package com.example.time; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.content.SharedPreferences; import android.text.format.Time; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { SharedPreferences dateFile; Button writeDate, readDate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 指定一個檔案來儲存 dateFile = this.getSharedPreferences("DateFile", 0); // 宣告按鈕 writeDate = (Button) findViewById(R.id.button1); writeDate.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { //記錄當下時間日期 writeDate(); } }); readDate = (Button) findViewById(R.id.button2); readDate.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { //讀取時間日期 readDate(); } }); } public void writeDate() { // 取得時間 Time t = new Time(); t.setToNow(); String dateInfo = t.toString(); // 將字串寫入date裡 SharedPreferences.Editor e = dateFile.edit(); e.putString("date", dateInfo); e.commit(); Toast.makeText(this, "record Date is successful", Toast.LENGTH_LONG) .show(); } public void readDate() { String lastday = dateFile.getString("date", "2012"); // 讀取date裡的資料,如果date裡沒有資料,則會讀取預設值2012 Toast.makeText(this, lastday, Toast.LENGTH_LONG).show(); } }res/layout/activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/hello_world" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginTop="56dp" android:text="記錄日期undefinedrecord date)" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/textView1" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_marginBottom="22dp" android:text="讀取日期undefinedread date)" /> </RelativeLayout>結果:
沒有留言:
張貼留言