Preferences是一种应用程序内部轻量级的数据存储方案。
通过Context对象的getSharedPreferences方法获得的对象可以被同一应用程序下其他组件共享,而使用Activity对象的getPreferences方法获得的对象只能被调用该方法所在的Activity使用。
activity_preferences.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" >
<EditText
android:id="@+id/edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textNoSuggestions"/>
</RelativeLayout>
PreferencesActivity.java
package com.example.android.sample4;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.EditText;
import android.content.SharedPreferences;
public class PreferencesActivity extends Activity {
EditText editText;
SharedPreferences sp;
public final String EDIT_TEXT_KEY="EDIT_TEXT";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
editText = (EditText)this.findViewById(R.id.edit);
sp = getPreferences(MODE_PRIVATE);
setPreferences();
String result = sp.getString(EDIT_TEXT_KEY, null);
if(result != null)
{
editText.setText(result);
}
}
public void setPreferences()
{
SharedPreferences.Editor editor = sp.edit();
editor.putString(EDIT_TEXT_KEY, "test preferences");
editor.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_preferences, menu);
return true;
}
}