标签(空格分隔): Android
--
- 任务要求:
使用SharedPreferences将姓名和年龄信息保存到文件,然后再读取,如图所示。
思路:
就是使用sharePreference类存储数据,并在特定的时候用Toast显示存储的数据
在创建sharePreference类的对象后调用它的getsharepreference方法指定要存放数据的文件,如果没有系统自动创建这个文件,并设置文件的操作模式为私有化(其他应用无法访问)。然后创建sharePreference的editor来进行编辑。最后不要忘了调用editor对象的commit方法。读取数据也是如法炮制。创建sharePreference对象和editor对象调用个体getString方法通过对应的键值得到存储的数据然后将它显示出来
布局:
<EditText
android:id="@+id/edt_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/login" />
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#000000"/>
<EditText
android:id="@+id/edt_age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/age" />
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#000000"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/write"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="onClick"
android:text="@string/save"/>
<Button
android:id="@+id/read"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="onClick"
android:text="@string/read"/>
java文件:
1 获取相关控件
private Button write;
private Button read;
private EditText name;
private EditText password;
write = (Button)findViewById(R.id.write);
read = (Button)findViewById(R.id.read);
name = (EditText)findViewById(R.id.edt_name);
password = (EditText)findViewById(R.id.edt_age);
2建立监听事件
public void onClick(View view) {
String username = name.getText().toString();
String password1 = password.getText().toString();
switch (view.getId()){
case R.id.write:
saveToPre(username,password1);
break;
case R.id.read:
readPre();
break;
}
}
saveToPre方法和readPre方法:
private void readPre() {
SharedPreferences sp = getSharedPreferences("name",MODE_PRIVATE);
String username = sp.getString("xm","");
String age = sp.getString("m","");
name.setText("");
password.setText("");
Toast.makeText(this,"姓名是:" + username + " 年龄是:" + age,Toast.LENGTH_LONG).show();
}
private boolean saveToPre(String username, String password) {
SharedPreferences sp = getSharedPreferences("name",MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putString("xm",username);
edit.putString("m",password);
edit.apply();
Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
return true;
}
效果展示: