MainActivity类的内容
public class MainActivity extends Activity {
EditText nameValue = null;
EditText ageValue = null;
PreferencesService service = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nameValue = (EditText) findViewById(R.id.name_id); //获取名字输入框id
ageValue = (EditText) findViewById(R.id.age_id); //获取年龄输入框id
service = new PreferencesService(getApplication());
Map<String, String> map = service.getPreferenves();
nameValue.setText(map.get("name")); //获得配置参数name
ageValue.setText(map.get("age")); //获得配置参数age
}
public void save(View v) throws Exception {
String name = nameValue.getText().toString(); //获取输入的名字
String age = ageValue.getText().toString(); //获取输入的年龄
service.save(name, Integer.valueOf(age)); //执行保存方法
Toast.makeText(getApplicationContext(), R.string.success,
Toast.LENGTH_LONG).show(); //吐丝显示保存成功
}
}
PreferencesService类的内容
public class PreferencesService {
Context context;
public PreferencesService(Context context) {
this.context = context;
}
/**
* 保存参数
* @param name 姓名
* @param age 年龄
*/
public void save(String name, Integer age) {
//确定文件名称,并把文件读写设置成Context.MODE_PRIVATE
SharedPreferences preferences = context.getSharedPreferences("itcast",Context.MODE_PRIVATE );
//创建xml编辑器
Editor editor = preferences.edit();
editor.putString("name", name); //第一个参数是为xml节点起名字,第二个参数是为节点写入值
editor.putInt("age", age);
editor.commit(); //未调用该方法之前,信息存储在内存中,调用后写成xml文件
}
/**
* 获取各项配置参数
* @return
*/
public Map<String,String> getPreferenves (){
Map<String, String> map = new HashMap<String, String>();
SharedPreferences preferences = context.getSharedPreferences("itcast",Context.MODE_PRIVATE );
map.put("name", preferences.getString("name", ""));
map.put("age", String.valueOf(preferences.getInt("age", 0)));
return map;
}
}