SharedPreferences
一、XML代码界面布局
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="姓名:"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="25sp"
android:gravity="center"/>
<EditText
android:id="@+id/name"
android:layout_width="0dp"
android:textSize="25sp"
android:layout_height="wrap_content"
android:layout_weight="4"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="密码:"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="25sp"
android:gravity="center"/>
<EditText
android:id="@+id/password"
android:layout_width="0dp"
android:textSize="25sp"
android:layout_height="wrap_content"
android:layout_weight="4"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/write"
android:text="写入"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="25sp"
android:onClick="onClick"/>
<Button
android:id="@+id/read"
android:text="读取"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="25sp"
android:onClick="onClick"/>
</LinearLayout>
二、JAVA代码及功能实现
public class MainActivity extends AppCompatActivity {
private EditText name;
private EditText password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.name);
password = (EditText) findViewById(R.id.password);
}
public void onClick(View view) {
switch (view.getId()){
case R.id.write:
String name = name.getText().toString();
String password = password.getText().toString();
if(saveToPrefs(password,name)){
Toast.makeText(MainActivity.this,"写入完毕",Toast.LENGTH_SHORT).show();
}
break;
case R.id.read:
readFromPrefs();
break;
}
}
private void readFromPrefs() {
SharedPreferences preferences = getSharedPreferences("customer.txt",MODE_PRIVATE);
String name=preferences.getString("name","");
String password=preferences.getString("password","");
password.setText(password);
name.setText(name);
}
private boolean saveToPrefs(String password, String name) {
SharedPreferences preferences = MainActivity.this.getSharedPreferences("customer.txt",MODE_PRIVATE);
SharedPreferences.Editor editor =preferences.edit();
editor.putString("name",name);
editor.putString("password",password);
editor.commit();
return true;
}
}