一、运行效果图
二、核心代码
LoginActivity.java
package com.example.minitwittersimulate;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
private EditText etUsername;
private EditText etPassword;
private CheckBox cbRememberPass;
private Button btnLogin;
protected SharedPreferences mSpSettings = null;
private static final String PREFS_NAME = "NamePwd";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
cbRememberPass = (CheckBox) findViewById(R.id.cbRememberPass);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
if ("admin".equals(etUsername.getText().toString())
&& "123456".equals(etPassword.getText().toString())) {
// 判断用户名和密码
if (cbRememberPass.isChecked()) {
// 判断复选框是否选中
mSpSettings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
Editor edit = mSpSettings.edit();
edit.putBoolean("isKeeep", true);
edit.putString("username", etUsername.getText()
.toString());
edit.putString("password", etPassword.getText()
.toString());
edit.commit();
// 选中后记住密码
} else {
mSpSettings = getSharedPreferences(PREFS_NAME,
MODE_PRIVATE);
Editor edit = mSpSettings.edit();
edit.putBoolean("isKeeep", false);
edit.putString("username", "");
edit.putString("password", "");
edit.commit();
// 未选中没有记住密码
}
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "用户名或密码错误",
Toast.LENGTH_SHORT).show();
}
}
});
getData();
}
protected void onResume() {
super.onResume();
getData();
}// 在界面显示之前得到数据
private void getData() {
// TODO Auto-generated method stub
mSpSettings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
if (mSpSettings.getBoolean("isKeep", true)) {
etUsername.setText(mSpSettings.getString("username", ""));
etPassword.setText(mSpSettings.getString("password", ""));
}// 如果之前存储过,则显示在相应的文本里
else {
etUsername.setText("");
etPassword.setText("");
}// 如果之前没有显示过,则显示为空。
}
}
三、运行中遇到的问题
对安卓中各函数的使用及作用不熟悉,写代码的过程中出现很多问题。