Android参数偏好设置,并且回显
1、开发的软件需要软件参数设置功能,用户根据自己的偏好,选择合适的参数。
例如,在Eclipse里面的windows ——》preference就是设置偏好的。
2、Eclipse通过xml文件保存用户偏好参数,使用sharePreference接口保存用户在软件设置的参数。我们不需要和生成的xml打交道,sharePreference会处理。
3、实例Demo
a、实现如下功能,保存用户设置的姓名、年龄参数。

对应的xml文件
<?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="姓名" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/name"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="年龄" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numeric="integer"
android:id="@+id/age"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="保存"
android:onClick="test"
/>
</LinearLayout>b、MainActivity.java
1、定义成员变量
private EditText nameText;
private EditText ageText;
private Button button1;
2、找到xml里面对应的对象
ageText=(EditText) this.findViewById(R.id.age);
nameText= (EditText) this.findViewById(R.id.name);
3、注册button按钮的单击事件
A、button1.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
String name=nameText.getText().toString();
String age=ageText.getText().toString();
save();//把Android程序用户提交的数据保存到文件中(内存到硬盘)
show()//把文件里的数据放到Android程序里。即实现了回显功能。
}
}
);
private void save(){
SharedPreferences preference=MainActivity.this.getSharedPreference("itcast",this.MODE_PRIVATE);//两个参数,第一个是文件名,第二个是模式,一般设为私有。
Editor editor=preferences.edit();
editor.putString("name", name);//内存,到硬盘.
editor.putInt("age", Integer.valueOf(age));
editor.commit();
}

对应的XML文件(preference生成的)FileExploer里面


导出
吃、接下来就是回显,实现show函数。也就是从把xml文件的值读到android程序里。
private void show(){
SharedPreferences preference=MainActivity.this.getSharedPreference("itcast",this.MODE_PRIVATE);
nameText.setText( preference.getString("name",""));//默认值为“”
ageText.setText(new String(preference.getInt("age",0)));//默认值为0
}