例如要保存用户的姓名和年龄两个参数,如下图布局
1.在strings.xml文件中声明要使用到的字符串
2.在布局文件中添加<TextView/>,<EditText/>,<Button />控件,实现上图的布局
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/name" />
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/name" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/age" />
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numeric="integer"
android:id="@+id/age" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button"
android:onClick="save"
/>
public class MainActivity extends Activity {
private EditText nameText;
private EditText ageText;
private PreferencesService service;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nameText = (EditText)this.findViewById(R.id.name);
ageText = (EditText)this.findViewById(R.id.age);
service = new PreferencesService(this);//每次点击保存都会实例化该方法
}
public void save(View v) {
String name = nameText.getText().toString();
String age = ageText.getText().toString();
//PreferencesService service = new PreferencesService(this);//每次点击保存都会实例化,放到启动方法中
service.save(name,Integer.valueOf(age));
Toast.makeText(getApplicationContext(), R.string.success, 1).show();
}
}
4.PreferencesService类的代码如下
public class PreferencesService {
private Context context;
public PreferencesService(Context context) {//得到上下对象
this.context = context;
}
/**
* 保存参数
* @param name
* @param age
*/
public void save(String name, Integer age) {
//取得SharePreferences对象,通过上下文环境得到
SharedPreferences preferences = context.getSharedPreferences("gao", Context.MODE_PRIVATE);
Editor editor = preferences.edit();//得到编辑器对象
editor.putString("name", name);
editor.putInt("age", age);//到此数据保存在内存中
editor.commit();//把内存中的数据提交到文件中
}
}
运行结果产生的xml文件中的数据
以上即实现了用户自己对软件偏好参数的保存,那么如何读取用户的偏好参数呢?如用户打开上述软件时,显示用户的参数设置,如下图
实现方法是,在PreferencesService类中添加getPreferences()方法,具体代码如下
/**
* 获取各项配置参数
* @return 参数值
*/
public Map<String,String> getPreferences(){
Map<String,String> params = new HashMap<String,String>();
//取得SharePreferences对象,通过上下文环境得到,"gao"是之前保存好的数据名称,注意不带后缀名
SharedPreferences preferences = context.getSharedPreferences("gao", Context.MODE_PRIVATE);
params.put("name", preferences.getString("name", "you name"));
params.put("age", String.valueOf(preferences.getInt("age", 0)));
return params;
}
//第一次运行时显示参数
Map<String,String> params = service.getPreferences();
nameText.setText(params.get("name"));
ageText.setText(params.get("age"));
注:附件文章中的代码。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。