標簽(空格分隔): 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;
}
效果展示: