XML文件
<?xml version="1.0" encoding="utf-8"?> <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" tools:context="com.example.dell.wodelianxi.denglucunchu" android:background="@drawable/beijing" android:orientation="vertical"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入用户名" android:id="@+id/et_user"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="numberPassword" android:hint="请输入密码" android:id="@+id/et_pwd"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="保存用户名、密码" android:layout_weight="1" android:id="@+id/cb_jizhu"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="注册" android:layout_weight="2" android:background="@drawable/zhuce" android:id="@+id/zhuce"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="登陆" android:layout_weight="2" android:background="@drawable/zhuce" android:id="@+id/denglu" android:onClick="denglu"/> </LinearLayout> </LinearLayout>
JAVA代码
package com.example.dell.wodelianxi; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; public class denglucunchu extends AppCompatActivity { EditText et_user; EditText et_pwd; CheckBox cb_jizhu; SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_denglucunchu); sp = getSharedPreferences("info", MODE_PRIVATE); et_user = (EditText)findViewById(R.id.et_user); et_pwd = (EditText)findViewById(R.id.et_pwd); cb_jizhu = (CheckBox)findViewById(R.id.cb_jizhu); et_user.setText(sp.getString("user",null)); et_pwd.setText(sp.getString("password",null)); } public void denglu(View view) { if (cb_jizhu.isChecked()) { SharedPreferences.Editor editor = sp.edit(); String user = et_user.getText().toString(); String password = et_pwd.getText().toString(); if(TextUtils.isEmpty(user) || TextUtils.isEmpty(password)) { Toast.makeText(denglucunchu.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show(); } else { editor.putString("user", user); editor.putString("password", password); //editor.putString(user,password); editor.commit(); Toast.makeText(denglucunchu.this, "保存成功", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(denglucunchu.this, "请保存用户名、密码", Toast.LENGTH_SHORT).show(); } } }
原文:http://www.cnblogs.com/youshashuosha/p/5370345.html