Android存储方式有很多种,在这里所用的存储方式是SharedPreferrences, 其采用了Map数据结构来存储数据,以键值的方式存储,可以简单的读取与写入。所以比较适合我们今天做的这个项目。我们来看一下运行图:
一.布局界面
1.login_top.xml
<&#63;xml version="1.0" encoding="utf-8"&#63;>
2.activity_main.xml
<&#63;xml version="1.0" encoding="utf-8"&#63;>
3.activity_welcome.xml
<&#63;xml version="1.0" encoding="utf-8"&#63;>
二.MainActivity
public class MainActivity extends AppCompatActivity { private EditText etName; private EditText etPassword; private SharedPreferences sharedPreferences; private CheckBox cbremenber; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews(); sharedPreferences=getSharedPreferences("remenberpassword", Context.MODE_PRIVATE); boolean isRemember=sharedPreferences.getBoolean("remenberpassword",false); if(isRemember) { String name = sharedPreferences.getString("name", ""); String password = sharedPreferences.getString("password", ""); etName.setText(name); etPassword.setText(password); cbremenber.setChecked(true); } } private void initViews() { etName=(EditText) findViewById(R.id.etName); etPassword=(EditText) findViewById(R.id.etPassword); cbremenber=(CheckBox)findViewById(R.id.cbremenber); } public void login(View view){ String name=etName.getText().toString(); String password=etPassword.getText().toString(); if("admin".equals(name)&&"123456".equals(password)){ SharedPreferences.Editor editor= sharedPreferences.edit(); if(cbremenber.isChecked()){ editor.putBoolean("remenberpassword",true); editor.putString("name",name); editor.putString("password",password); }else { editor.clear(); } editor.commit(); Intent intent=new Intent(this,WelcomeActivity.class); startActivity(intent); finish(); }else { Toast.makeText(this,"账号或密码有误",Toast.LENGTH_LONG).show(); } } }
三.WelcomeActivity
public class WelcomeActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。