1.看我博客的人一般都知道,我呢首先就是先写布局文件
<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/edit_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="请输入账号" />
<EditText
android:id="@+id/edit_pwd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="请输入密码"
android:password="true" />
<CheckBox
android:id="@+id/check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="记住密码" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="login"
android:text="登录" />
</LinearLayout>
2.然后就是写你在Activity当中的方法
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText edit_name;
private EditText edit_pwd;
private CheckBox check_box;
private SharedPreferences sp;
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit_name = (EditText) findViewById(R.id.edit_name);
edit_pwd = (EditText) findViewById(R.id.edit_pwd);
check_box = (CheckBox) findViewById(R.id.check_box);
sp = getSharedPreferences("config", Context.MODE_WORLD_READABLE);
boolean flag = sp.getBoolean("flag", false);
check_box.setChecked(flag);
if (flag) {
String newName = sp.getString("name", "");
String newPwd = sp.getString("pwd", "");
edit_name.setText(newName);
edit_pwd.setText(newPwd);
}
}
public void login(View view){
String name = edit_name.getText().toString();
String pwd = edit_pwd.getText().toString();
if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) {
Toast.makeText(MainActivity.this, "输入不能为空", 0).show();
}else{
Editor editor = sp.edit();
if (check_box.isChecked()) {
editor.putBoolean("flag", true);
editor.putString("name", name);
editor.putString("pwd", pwd);
editor.commit();
}else{
editor.putBoolean("flag",false).commit();
}
Intent intent = new Intent(MainActivity.this,ShowActivity.class);
startActivity(intent);
finish();
}
}
}
————这样你第二次,就可以记住你的密码了