布局
<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" >
<EditText
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="UserName" />
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />
<Button
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="login" />
<Button
android:id="@+id/btn_exit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="exit" />
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
Button btn_login, btn_exit;
EditText et_username, et_password;
private String username = "zhangsan";
private String password = "123";
private SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
/*
* 初始化
*/
private void init() {
btn_login = (Button) findViewById(R.id.btn_login);
btn_exit = (Button) findViewById(R.id.btn_exit);
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
btn_login.setOnClickListener(this);
btn_exit.setOnClickListener(this);
sp = getSharedPreferences("UserInfo", MODE_PRIVATE);
// 填充以保存的账号密码
et_username.setText(sp.getString("username", ""));
et_password.setText(sp.getString("password", ""));
}
/*
* 监听器
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_login:
String tUserName = et_username.getText() + "";
String tPassword = et_password.getText() + "";
Editor editor = sp.edit();
// String tPassword = et_password.getText().toString();
if (tUserName.equals(username) && tPassword.equals(password)) {
// 保存账号密码
editor.putString("username", tUserName);
editor.putString("password", tPassword);
editor.commit();
Toast.makeText(this, "已登录", Toast.LENGTH_SHORT).show();
} else {
et_username.setText("");
et_password.setText("");
// 清空密码
editor.putString("username", "");
editor.putString("password", "");
editor.commit();
Toast.makeText(this, "未登录,账号或密码错误!", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn_exit:
finish();
break;
}
}
}