LoginActivity代码如下:
package cn.edu.bzu.a01; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; public class LoginActivity extends AppCompatActivity { private EditText etName; private EditText etPassword; private CheckBox cbIsRememberPass; private SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); initView(); sharedPreferences=getSharedPreferences("data", Context.MODE_PRIVATE); boolean isRemember=sharedPreferences.getBoolean("rememberpassword",false); if (isRemember){ String name=sharedPreferences.getString("name",""); String password=sharedPreferences.getString("password",""); etName.setText(name); etPassword.setText(password); cbIsRememberPass.setChecked(true); } } private void initView() { etName= (EditText) findViewById(R.id.etName); etPassword= (EditText) findViewById(R.id.etPassword); cbIsRememberPass= (CheckBox) findViewById(R.id.cbIsRememberPass); } 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(cbIsRememberPass.isChecked()){ editor.putBoolean("rememberpassword",true); editor.putString("name",name); editor.putString("password",password); }else{ editor.clear(); } editor.commit(); Intent intent=new Intent(this,MainActivity.class); startActivity(intent); finish(); }else{ Toast.makeText(this, "账号或密码错误", Toast.LENGTH_SHORT).show(); } } }
MainActivity中代码如下:
package cn.edu.bzu.a01; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
layout中activity_login.xml代码:
<?xml version="1.0" encoding=
版权声明:本文为yuzaijun原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。