用sharepreferences寫了一點存放配置信息

我用sharepreferences寫了一個簡單的記住密碼和賬號
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:id="@+id/activity_main"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="zking.com.ass.MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入用戶名:"
        android:id="@+id/yhm_name"
        />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入密碼:"
        android:id="@+id/qrr_pass"
        />
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存密碼"
        android:id="@+id/jizhumima"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登錄"
        android:onClick="login"
        />
</LinearLayout>

得到sharepreferences (文件,xml–>鍵值對Map)
Context.MODE_PRIVATE是默認模式,是私有的只能被本身訪問,在這種模式下原來的數據會被新寫入的數據替代。

       SharedPreferences sp= getSharedPreferences("loginfo", Context.MODE_PRIVATE);
        ed = sp.edit();
        //取數據      然後賦值到yhm_name
        String name=sp.getString("name","");
        yhm_name.setText(name);

        //這裏的就是說如果你點擊了記住密碼 在登錄的話信息就會記住
        boolean aa=sp.getBoolean("isRemember",false);
        if (aa){
            String pass=sp.getString("pass","");
            qrr_pass.setText(pass);
        }
        jizhumima.setChecked(aa);

下面的代碼就是說你點擊的登錄就會觸發一個方法吧信息存入sharepreferences

 public void login(View view){
        //獲取用戶名密碼
        String name=yhm_name.getText().toString();
        String pwd=qrr_pass.getText().toString();
        //判斷是否記住密碼
        if (jizhumima.isChecked()){
        //存()
            ed.putString("name",name);
            ed.putString("pass",pwd);
            ed.putBoolean("isRemember",true);
        }
        else{
        //不存(只記住賬號)
            ed.putString("name",name);
            ed.putBoolean("isRemember",false);
        }
        ed.commit();
    }

這個是點擊登錄後的效果
效果圖如下:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章