package com.example.administrator.mytestapp.SP; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.example.administrator.mytestapp.R; public class TestSP extends AppCompatActivity { private static final String TAG="SharedPreferencesDemo"; private static final String LOGIN_DATA="LoginData"; private EditText nameFiled,pwdFiled; private Button loginBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_sp); nameFiled= (EditText) findViewById(R.id.name); pwdFiled= (EditText) findViewById(R.id.password); loginBtn= (Button) findViewById(R.id.login); loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setTitle("Name:"+nameFiled.getText().toString()+"&Password"+pwdFiled.getText().toString()); } }); SharedPreferences loginData=getSharedPreferences(LOGIN_DATA,0); String name=loginData.getString("Name",""); String password=loginData.getString("Password",""); nameFiled.setText(name); pwdFiled.setText(password); } @Override protected void onStop() { SharedPreferences loginData=getSharedPreferences(LOGIN_DATA,0); SharedPreferences.Editor mEditor=loginData.edit(); mEditor.putString("Name",nameFiled.getText().toString()); mEditor.putString("Password",pwdFiled.getText().toString()); mEditor.commit(); super.onStop(); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.administrator.mytestapp.SP.TestSP"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/name" android:hint="姓名"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="密码" android:id="@+id/password"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="login" android:id="@+id/login"/> </LinearLayout>