您的位置:首页 > 移动开发 > Android开发

Android——登录界面、SharedPreferences实现记住密码等账户信息

2016-06-11 23:26 501 查看
先看下效果图:



该界面的布局文件为:

<?xml version="1.0" encoding="utf-8"?>
<TableLayout 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:stretchColumns="1"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
tools:context="xjtu.com.rememberpwd.MainActivity">

<TableRow>
<TextView android:text="账号:"
android:paddingLeft="30dp"/>
<EditText android:id="@+id/username"
android:background="@drawable/et_shape"/>
</TableRow>

<TableRow android:layout_marginTop="10dp">

<TextView android:text="密码:"
android:paddingLeft="30dp"/>
<EditText android:id="@+id/password"
android:background="@drawable/et_shape"
android:inputType="textPassword"/>
</TableRow>

<TableRow android:layout_marginTop="10dp">

<CheckBox android:id="@+id/chk"
android:text="记住密码"/>
<Button android:id="@+id/btn_login"
android:background="@drawable/btn_shape"
android:text="登录"/>

</TableRow>

</TableLayout>


业务逻辑代码为:

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.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

private Button btn_login;
private EditText username,password;
private CheckBox chk;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
restoreInfo();
}

private void initView(){
btn_login=(Button)findViewById(R.id.btn_login);
username=(EditText)findViewById(R.id.username);
password=(EditText)findViewById(R.id.password);
chk=(CheckBox)findViewById(R.id.chk);

btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (chk.isChecked()){
String usr=username.getText().toString();
String pwd=password.getText().toString();
memInfo(usr,pwd);
}else{
SharedPreferences.Editor et=getSharedPreferences("data",0).edit();
et.clear();
et.commit();
}
Intent intent=new Intent(MainActivity.this,LoginSuccess.class);
startActivity(intent);
}
});

}

private void memInfo(String usr,String pwd){
SharedPreferences.Editor editor=getSharedPreferences("data",0).edit();
editor.putString("username",usr);
editor.putString("password",pwd);
editor.commit();
}

private void restoreInfo(){
SharedPreferences sp=getSharedPreferences("data",0);
username.setText(sp.getString("username",""));
password.setText(sp.getString("password",""));
}

}
主要思想:在输入登录信息后,点击“登录”前,如果勾选记住密码,此时,点击“登录”会调用memInfo方法把信息用SharedPrefenerces技术存入文件名为data的文件中。软件每次启动时会在onCreate方法中把保存的信息恢复并自动回填到到相应的EditText中(第一次启动没有,因为还没有创建data文件)。如果不勾选,就不会记住密码,就算之前记住了,也会清空,因为data文件被清空。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息