Android组件学习笔记(SharedPreferences实现保存)

可以记住信息,即使退出也会保存下来,继续使用

简单的登录界面

源代码:

package com.example.hp.keepbaocun;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
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;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity  {
    EditText userName,userPass;
    CheckBox saveInfo;
    SharedPreferences pref;
    SharedPreferences.Editor editor;
    Button btn_Login;
    Button btn_Cancel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        userName = (EditText) findViewById(R.id.user_name);
        userPass = (EditText) findViewById(R.id.user_pass);
        saveInfo = (CheckBox) findViewById(R.id.save_info);
        Button btn_Login = (Button) findViewById(R.id.btn_login);
        Button btn_Cancel = (Button) findViewById(R.id.btn_cancel);
        //私密的模式存储XML文件,XML文件名为UserInfo
        pref = getSharedPreferences("UserInfo",MODE_PRIVATE);
        //两个参数,第一个参数是preferece的名称(比如:MyPref),第二个参数是打开的方式(一般选择private方式)
        editor = pref.edit();
        String name = pref.getString("userName","");

        if (name == null){saveInfo.setChecked(false);}
        else {saveInfo.setChecked(true);userName.setText(name);}
        btn_Login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.btn_login:
                        String  name = userName.getText().toString().trim();//trim()函数的功能是去掉首尾空格
                        String pass = userPass.getText().toString().trim();
                        if ("admin".equals(name) && "123456".equals(pass)){
                            if (saveInfo.isChecked()){
                                editor.putString("userName",name);
                                editor.commit();
                            }else {
                                editor.remove("userName");
                                editor.commit();
                            }
                            Toast.makeText(MainActivity.this,"登陆成功",Toast.LENGTH_LONG).show();
                        }else {
                            Toast.makeText(MainActivity.this,"禁止登陆",Toast.LENGTH_LONG).show();
                        }
                }
            }
        });
    }
}


布局代码:



    
    
    
    
    
    

你可能感兴趣的:(Android)