这段代码中:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);Manifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.preference.test" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".PreferenceTestActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Preference Test" /> <EditText android:id="@+id/EditText01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:height="180px" android:text="" > </EditText> <Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send" > </Button> </LinearLayout>
package com.preference.test; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; public class PreferenceTestActivity extends Activity { private EditText myEditText; private Button myBtn; public static final String SEND_SMS = "temp_sms"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myEditText = (EditText)findViewById(R.id.EditText01); myBtn = (Button)findViewById(R.id.Button01); SharedPreferences pre = getSharedPreferences(SEND_SMS, MODE_WORLD_READABLE); String content = pre.getString("sms_context", ""); myEditText.setText(content); } @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); SharedPreferences.Editor editor = getSharedPreferences(SEND_SMS, MODE_WORLD_READABLE).edit(); editor.putString("sms_context", myEditText.getText().toString()); editor.commit(); } }