1.activity_shared_preferences.xml文件中
<!-- 要保存的数据 -->
<EditText
android:id="@+id/et_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:ems="10" >
<requestFocus />
</EditText>
<!-- 将输入的信息保存到SharedPreferences中 -->
<Button
android:id="@+id/btnSave2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/et_content"
android:text="保存到SharedPreferences"
android:onClick="save2"/>
<!-- 读取SharedPreferences中的信息 -->
<Button
android:id="@+id/btn_load"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btnSave2"
android:layout_below="@+id/btnSave2"
android:text="读取"
android:onClick="load2"/>
<TextView
android:id="@+id/tvShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/btn_load"
android:layout_alignBottom="@+id/btn_load"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@+id/btn_load"
android:text="" />
2.SharedPreferencesActivity活动中
package com.t20.fileop;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class SharedPreferencesActivity extends Activity {
private EditText et_content;
private TextView tvShow;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shared_preferences);
// 获得相应控件
et_content = (EditText) findViewById(R.id.et_content);
tvShow = (TextView) findViewById(R.id.tvShow);
}
/**
* 将输入的信息保存到SharedPreferences中 不需要权限
*
* @param v
*/
public void save2(View v) {
//要保存的数据
String str = et_content.getText().toString();
//获取SharedPreferences(关联共享)对象
SharedPreferences sp = getSharedPreferences("dataSp",
Context.MODE_PRIVATE);
// 编辑器
Editor editor = sp.edit();
//利用编辑器存储数据,利用键值对形式存储
editor.putString("name", str);
editor.putInt("age", 18);
// 提交,利用commit提交有返回值,editor.apply()提交没有返回值
boolean flag = editor.commit();
if (flag) {// 如果保存成功则给出成功的提示
Toast.makeText(SharedPreferencesActivity.this, "保存成功!",
Toast.LENGTH_SHORT).show();
}
}
/**
* 读取SharedPreferences中的信息显示到文本中
* 读取不需要用到编辑器
* @param v
*/
public void load2(View v) {
//获取SharedPreferences(关联共享)对象
SharedPreferences sp = getSharedPreferences("dataSp",
Context.MODE_PRIVATE);
//获取SharedPreferences中的数据
String name = sp.getString("name", "");
Integer age = sp.getInt("age", 0);
String str="姓名:"+name+",年龄是:"+age+"";
tvShow.setText(str);
}
}