Android使用指南之sharedpreference

Android使用之sharedPreferences

今天在写登录界面,在实现记住密码和自动登陆的时候,用到了sharedPreferences 这里做个小小的总结。主要是最近发现自己老了,不写下来就忘了!有时候觉得人健忘也未必不是件好事对吧。不扯淡了,进入正题。

sharedPreferences 可以用来进行数据的共享,包括应用程序之间,或者同一个应用程序中的不同组件。比如两个activity除了通过Intent传递数据之外,也可以通过SharedPreferences来共享数据。

定义共享偏好

SharedPreferences sharedata = getSharedPreferences(“data”, 0);

存数据

Editor sharedata = getSharedPreferences(“data”, 0).edit();

sharedata.putString(“item”,”hello getSharedPreferences”);

sharedata.commit();

读数据

String data = sharedata.getString(“item”, null);

通过SharedPreferences可以保存程序的某些配置信息,而程序员不需要知道它到底以什么形式保存的,保存在了什么地方。

在Android系统中,SharedPreferences中的信息以XML文件的形式保存在 /data/data/PACKAGE_NAME/shared_prefs目录下。


用户登陆界面

从百度上面copy了那么多,感觉没有什么鸟可以用嘛,事实证明有代码才是王道。毕竟有位帅的一逼的屌丝曾说过这样的一句话:能用代码说话的时候,就别瞎逼逼!——电科彭于晏

这个用户登陆界面的demo,相对比较粗糙,没有加入相对fashion的动画,毕竟那个不是本文的重点,各位老铁莫要觉得扎心,毕竟本人还是比较走心的!

1. 界面实现功能:

1、能够判断用户的账号密码正确后(由于没有加后台服务器,这里只是简单判读程序的默认账号密码,相信在不久的将来本帅会分享给大家包括服务器和数据库在内的相对比较完整的开源程序),才能实现记住密码,和自动登陆的功能;

2、记住密码和自动登录功能,默认的情况下是不选择的;

3、使用上文提到的sharedPreferences实现再次打开应用的时候能根据本地信息自动选择是否去勾选显示相应控件的状态;

4、清空按钮,在没有信息输入的时候清空按钮是不会显示的,在有信息输入的时候才会有显示,点击后自动清空内容;

2. 登陆界面显示效果:

2.1 效果图

不喜勿喷,因为你喷我的话,我会喷回去的!

ogin

2.2 登陆界面代码XML
<?xml version="1.0" encoding="utf-8"?>
<!-- android:focusable="true"
  android:focusableInTouchMode="true"
  把EditText默认的行为截断了! -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.android.kimhlo.smartfeedapplication.LoginActivity"
    android:orientation="vertical"
    android:padding="16dp"
    android:background="#ECEDF1"
    android:focusable="true"
    android:focusableInTouchMode="true">

    <ImageView
        android:layout_width="90dp"
        android:layout_height="0dp"
        android:layout_weight="0.5"
        android:layout_gravity="center"
        android:src="@drawable/ic_account_circle_black_48dp"
        android:id="@+id/account_image"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical"
        android:weightSum="1">

        <!--第一行输入账号-->
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/account_edit_text"
                android:layout_width="match_parent"
                android:layout_height="48dp"
                android:gravity="center"
                android:hint="@string/account_name_hint"
                android:inputType="textPersonName"
                android:textColor="#bd6c1f"
                android:textColorHint="#CCADAD" />

            <ImageView
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:src="@drawable/ic_account_box_black_24dp" />

            <ImageView
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:src="@drawable/ic_clear_black_48dp"
                android:visibility="invisible"
                android:id="@+id/clear_account_name_image_view"
                android:layout_centerVertical="true"
                android:layout_alignParentEnd="true" />
        </RelativeLayout>

        <!--第二行输入密码-->
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/password_edit_text"
                android:layout_width="match_parent"
                android:layout_height="48dp"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:gravity="center"
                android:hint="@string/account_password_hint"
                android:inputType="textPassword"
                android:textColor="#bd6c1f"
                android:textColorHint="#CCADAD" />

            <ImageView
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:src="@drawable/ic_lock_outline_black_48dp" />

            <ImageView
                android:id="@+id/visibility_image_view"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_alignParentEnd="true"
                android:layout_centerVertical="true"
                android:src="@drawable/ic_visibility_off_black_48dp" />

            <ImageView
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_centerVertical="true"
                android:layout_marginEnd="5dp"
                android:layout_toStartOf="@+id/visibility_image_view"
                android:src="@drawable/ic_clear_black_48dp"
                android:visibility="invisible"
                android:id="@+id/clear_password_image_view"/>
        </RelativeLayout>
        <!--登陆的按钮-->
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <CheckBox
                android:id="@+id/remember_password_check_box"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/remember_password"
                android:textColor="#000000" />

            <CheckBox
                android:id="@+id/login_auto_check_box"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/remember_password_check_box"
                android:text="@string/login_auto"
                android:textColor="#000000" />
            <Button
                android:id="@+id/login_button"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_gravity="center_horizontal"
                android:background="@drawable/ic_pets_black_48dp"
                android:layout_toRightOf="@id/remember_password_check_box"
                android:layout_marginLeft="70dp" />
        </RelativeLayout>
    </LinearLayout>
</LinearLayout>

3. Activity代码(对应上文中的layout)

下面开始是讲知识点了,赶紧拿上小板凳和笔记本!

3.1 实现功能代码说明
3.1.1 共享偏好功能
  1. 定义
//定义共享偏好
sp=this.getSharedPreferences("userInfo",0);
  1. 根据相应的控件在userInfo中添加对应的信息

    记住密码和自动登陆信息添加和改变

    浓缩就是精华,将百度那些浓缩一下: sp.edit().putBoolean(“ISCHECK”,true).commit();

    切记一定要commit,这种废话我就不说三遍了,就跟github一样如果你最后不commit也不会有什么鸟用。

//记住密码多选框的监听事件    
rememberPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (rememberPassword.isChecked()){
                //将记住密码设置为true
                sp.edit().putBoolean("ISCHECK",true).commit();
                Toast.makeText(LoginActivity.this,"记住密码",Toast.LENGTH_SHORT).show();
            }else {
                //否则设置为false
                sp.edit().putBoolean("ISCHECK",false).commit();
                Toast.makeText(LoginActivity.this,"不记住密码",Toast.LENGTH_SHORT).show();
            }
        }
    });

    //自动登陆多选框的监听事件
    autoLogin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (autoLogin.isChecked()){
                sp.edit().putBoolean("AUTO_LOGIN_ISCHECK",true).commit();
                Toast.makeText(LoginActivity.this,"自动登陆",Toast.LENGTH_SHORT).show();
            }else {
                sp.edit().putBoolean("AUTO_LOGIN_ISCHECK",false).commit();
                Toast.makeText(LoginActivity.this,"不自动登陆",Toast.LENGTH_SHORT).show();
            }
        }
    });
  1. 当你再次打开应用的时候就会根据下面的代码去读userInfo相应的信息

    老铁可能会有点懵,觉得加了判断了账户是否验证成功干嘛还要在EditText中设置账户的账号和密码,

    是因为如果我只点击了记住密码的情况下,应该显示上次登陆的账号和密码。

        if (sp.getBoolean("ISCHECK",true)&& sp.getBoolean("ACCOUNT_VALIDATE",true)){        
        //勾选记录密码的状态
           rememberPassword.setChecked(true);
           accountName.setText(sp.getString("USER_NAME",""));
           accountPassword.setText(sp.getString("PASSWORD",""));
           if (sp.getBoolean("AUTO_LOGIN_ISCHECK",true)){
               //勾选自动登陆
               autoLogin.setChecked(true);
               //转接到登陆成功的界面
               Intent intent=new Intent(this,LogoActivity.class);
               startActivity(intent);
           }
       }
  2. 登陆成功之后将相应的用户信息写入本地的userInfo

       //登陆按钮的监听事件,默认的登陆账号为:yang,密码为123456
    loginButton.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               nameValue=accountName.getText().toString();
               passwordValue=accountPassword.getText().toString();
               if (nameValue.equals("yang")&&passwordValue.equals("123456")){
                   Toast.makeText(LoginActivity.this,"账号和密码正确",Toast.LENGTH_SHORT).show();
                   if (rememberPassword.isChecked()){
                       Editor editor=sp.edit();
                       editor.putString("USER_NAME",nameValue);
                       editor.putString("PASSWORD",passwordValue);
                       editor.commit();
                   }
                   Intent intent=new Intent(LoginActivity.this,LogoActivity.class);
                   startActivity(intent);
                   //当输入的密码有效的时候将ACCOUNT_VALIDATE写为true
                   sp.edit().putBoolean("ACCOUNT_VALIDATE",true).commit();
               }else if (!nameValue.equals("kimhlo")){
                   Toast.makeText(LoginActivity.this,"输入的账号不存在",Toast.LENGTH_LONG).show();
                   //当输入密码有问题的时候ACCOUNT_VALIDATE写为false
                   sp.edit().putBoolean("ACCOUNT_VALIDATE",false).commit();
               }else if (!passwordValue.equals("123456")){
                   Toast.makeText(LoginActivity.this,"输入的密码错误",Toast.LENGTH_LONG).show();
               }
           }
       });
3.1.2 清空按钮的实现

清空按钮要通过监听EditText是否改变来实现,考虑到简介美观,就将TextWatcher重写成一个类,在onCreate中再用addTextChangedListener进行监听。至于清空功能,就直接点击之后将EditText写成“”就可以了,不再是详述。

<在onCreate中>

//对EditText进行监听
accountPassword.addTextChangedListener(new EditTextWatcher(accountPassword));
accountName.addTextChangedListener(new EditTextWatcher(accountName));

<在Activity的class中>

    /**
     * 对EditText进行实时监控,当有其中有东西输入的时候就显示清空按钮
     */
    class EditTextWatcher implements TextWatcher {

        private CharSequence temp;
        private EditText editText;

        //构造函数
        public EditTextWatcher(EditText inputEditText) {
            this.editText = inputEditText;
        }

        //int start开始的位置, int count被改变的旧内容数, int after改变后的内容数量
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            // 这里的s表示改变之前的内容,通常start和count组合,可以在s中读取本次改变字段中被改变的内容。
            // 而after表示改变后新的内容的数量。

        }

        @Override
        // int start开始的位置, int before改变前的内容数量, int count新增量
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            // 这里的s表示改变之后的内容,通常start和count组合,可以在s中读取本次改变字段中新的内容。
            //而before表示被改变的内容的数量。
            temp = s;
        }
        @Override
        // 表示最终内容
        public void afterTextChanged(Editable s) {
            if (temp.length()>0){
                if (editText==accountName){
                    clear_name.setVisibility(View.VISIBLE);
                }else if(editText==accountPassword){
                    clear_password.setVisibility(View.VISIBLE);
                }
            }else {
                if (editText==accountName){
                    clear_name.setVisibility(View.INVISIBLE);
                }else if(editText==accountPassword){
                    clear_password.setVisibility(View.INVISIBLE);
                }
            }
        }
    }

}
3.2 完整代码

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Image;
import android.provider.BaseColumns;
import android.content.SharedPreferences.Editor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Checkable;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import static android.R.attr.name;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;

public class LoginActivity extends AppCompatActivity {

    /**登陆界面的控件定义*/
    private EditText accountName;
    private EditText accountPassword;
    private ImageView clear_name;
    private ImageView clear_password;
    private Button loginButton;
    private CheckBox rememberPassword;
    private CheckBox autoLogin;

    /**定义用户的登录信息*/
    private String nameValue;
    private String passwordValue;

    /**定义共享设置*/
    private SharedPreferences sp;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
      //定义共享偏好
      sp=this.getSharedPreferences("userInfo",0);
        //初始化视图控件
        loginButton = (Button) findViewById(R.id.login_button);
        accountName = (EditText) findViewById(R.id.account_edit_text);
        accountPassword = (EditText) findViewById(R.id.password_edit_text);
        rememberPassword=(CheckBox) findViewById(R.id.remember_password_check_box);
        autoLogin=(CheckBox) findViewById(R.id.login_auto_check_box);
        clear_name=(ImageView) findViewById(R.id.clear_account_name_image_view);
        clear_password=(ImageView) findViewById(R.id.clear_password_image_view);

        //获得EditText中的账号和密码
        nameValue=accountName.getText().toString();
        passwordValue=accountPassword.getText().toString();

        /**
         * 当再次启动的时候只有当记住密码是勾选上的同时上次的账号密码得到验证后才可以实现
         * 记住密码和自动登陆
         */

        if (sp.getBoolean("ISCHECK",true)&& sp.getBoolean("ACCOUNT_VALIDATE",true)){
            //勾选记录密码的状态
            rememberPassword.setChecked(true);
            accountName.setText(sp.getString("USER_NAME",""));
            accountPassword.setText(sp.getString("PASSWORD",""));
            if (sp.getBoolean("AUTO_LOGIN_ISCHECK",true)){
                //勾选自动登陆
                autoLogin.setChecked(true);
                //转接到登陆的界面
                Intent intent=new Intent(this,LogoActivity.class);
                startActivity(intent);
            }
        }

        //登陆按钮的监听事件,默认的登陆账号为:yang,密码为123456
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nameValue=accountName.getText().toString();
                passwordValue=accountPassword.getText().toString();
                if (nameValue.equals("yang")&&passwordValue.equals("123456")){
                    Toast.makeText(LoginActivity.this,"账号和密码正确",Toast.LENGTH_SHORT).show();
                    if (rememberPassword.isChecked()){
                        Editor editor=sp.edit();
                        editor.putString("USER_NAME",nameValue);
                        editor.putString("PASSWORD",passwordValue);
                        editor.commit();
                    }
                    Intent intent=new Intent(LoginActivity.this,LogoActivity.class);
                    startActivity(intent);
                    //当输入的密码有效的时候将ACCOUNT_VALIDATE写为true
                    sp.edit().putBoolean("ACCOUNT_VALIDATE",true).commit();
                }else if (!nameValue.equals("kimhlo")){
                    Toast.makeText(LoginActivity.this,"输入的账号不存在",Toast.LENGTH_LONG).show();
                    //当输入密码有问题的时候ACCOUNT_VALIDATE写为false
                    sp.edit().putBoolean("ACCOUNT_VALIDATE",false).commit();
                }else if (!passwordValue.equals("123456")){
                    Toast.makeText(LoginActivity.this,"输入的密码错误",Toast.LENGTH_LONG).show();
                }
            }
        });

        //记住密码多选框的监听事件
        rememberPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (rememberPassword.isChecked()){
                    //将记住密码设置为true
                    sp.edit().putBoolean("ISCHECK",true).commit();
                    Toast.makeText(LoginActivity.this,"记住密码",Toast.LENGTH_SHORT).show();
                }else {
                    //否则设置为false
                    sp.edit().putBoolean("ISCHECK",false).commit();
                    Toast.makeText(LoginActivity.this,"不记住密码",Toast.LENGTH_SHORT).show();
                }
            }
        });

        //自动登陆多选框的监听事件
        autoLogin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (autoLogin.isChecked()){
                    sp.edit().putBoolean("AUTO_LOGIN_ISCHECK",true).commit();
                    Toast.makeText(LoginActivity.this,"自动登陆",Toast.LENGTH_SHORT).show();
                }else {
                    sp.edit().putBoolean("AUTO_LOGIN_ISCHECK",false).commit();
                    Toast.makeText(LoginActivity.this,"不自动登陆",Toast.LENGTH_SHORT).show();
                }
            }
        });

        //对EditText进行监听
        accountPassword.addTextChangedListener(new EditTextWatcher(accountPassword));
        accountName.addTextChangedListener(new EditTextWatcher(accountName));
        //对相应的清空按钮进行监听
        clear_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                accountName.setText("");
            }
        });
        clear_password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                accountPassword.setText("");
            }
        });
    }

    /**
     * 对EditText进行实时监控,当有其中有东西输入的时候就显示清空按钮
     */
    class EditTextWatcher implements TextWatcher {

        private CharSequence temp;
        private EditText editText;

        //构造函数
        public EditTextWatcher(EditText inputEditText) {
            this.editText = inputEditText;
        }

        //int start开始的位置, int count被改变的旧内容数, int after改变后的内容数量
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            // 这里的s表示改变之前的内容,通常start和count组合,可以在s中读取本次改变字段中被改变的内容。
            // 而after表示改变后新的内容的数量。

        }

        @Override
        // int start开始的位置, int before改变前的内容数量, int count新增量
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            // 这里的s表示改变之后的内容,通常start和count组合,可以在s中读取本次改变字段中新的内容。
            //而before表示被改变的内容的数量。
            temp = s;
        }
        @Override
        // 表示最终内容
        public void afterTextChanged(Editable s) {
            if (temp.length()>0){
                if (editText==accountName){
                    clear_name.setVisibility(View.VISIBLE);
                }else if(editText==accountPassword){
                    clear_password.setVisibility(View.VISIBLE);
                }
            }else {
                if (editText==accountName){
                    clear_name.setVisibility(View.INVISIBLE);
                }else if(editText==accountPassword){
                    clear_password.setVisibility(View.INVISIBLE);
                }
            }
        }
    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值