package com.example.asus.sharedpreferences; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; public class Main2Activity extends AppCompatActivity implements View.OnClickListener { private EditText name; private EditText password; private Button zc_bt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); initView(); } private void initView() { name = (EditText) findViewById(R.id.name); password = (EditText) findViewById(R.id.password); zc_bt = (Button) findViewById(R.id.zc_bt); zc_bt.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.zc_bt: String trim = name.getText().toString().trim(); String trim1 = password.getText().toString().trim(); //存储 SharedPreferences sp = getSharedPreferences("sp", 0); SharedPreferences.Editor edit = sp.edit(); edit.putString("name",trim); edit.putString("password",trim1); edit.commit(); //跳转 Intent intent = new Intent(this, MainActivity.class); startActivity(intent); break; } } }
package com.example.asus.sharedpreferences; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private EditText name; private EditText password; private Button dl_btn; private Button zc_btn; private LinearLayout activity_main; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { name = (EditText) findViewById(R.id.name); password = (EditText) findViewById(R.id.password); dl_btn = (Button) findViewById(R.id.dl_btn); zc_btn = (Button) findViewById(R.id.zc_btn); activity_main = (LinearLayout) findViewById(R.id.activity_main); dl_btn.setOnClickListener(this); zc_btn.setOnClickListener(this); //存储 SharedPreferences sp = getSharedPreferences("sp", 0); if (sp!=null){ //获取 String name1 = sp.getString("name", ""); String password1 = sp.getString("password", ""); //放入 name.setText(name1); password.setText(password1); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.dl_btn: break; case R.id.zc_btn: Intent intent = new Intent(this, Main2Activity.class); startActivity(intent); break; } } }