基于AndroidStudio的資料存盤(SharedPreferences存盤)的簡單應用
- 前言
- 一、登錄界面設計
- 二、MainActivity_10_5 中
前言
在手機的登錄界面輸入用戶名和密碼,點擊登錄按鈕后會將資料存盤在本地系統檔案中,下次再打開這個登錄界面時,系統會自動來判斷本地是否已經存在資料,若存在資料則直接顯示在EditTextView框中
一、登錄界面設計
效果圖:

代碼:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/txtusername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="用戶名:" />
<EditText
android:id="@+id/txtpasssword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="密碼:" />
<Button
android:id="@+id/btlogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="登錄" />
</LinearLayout>
二、MainActivity_10_5 中
代碼:
package com.example.upclass;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity_10_5 extends AppCompatActivity {
private EditText txtusername, txtpassword;
private Button btlogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_10_5);
txtusername = findViewById(R.id.txtusername);
txtpassword = findViewById(R.id.txtpasssword);
btlogin = findViewById(R.id.btlogin);
//按鈕點擊之后才出現的
final SharedPreferences sharedPreferences = getSharedPreferences("login", MODE_PRIVATE);
btlogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", txtusername.getText().toString());
editor.putString("password", txtpassword.getText().toString());
editor.apply();
}
});
String username = sharedPreferences.getString("username", "");
String password = sharedPreferences.getString("password", "");
if (!username.equals("") && !password.equals("")) {
txtusername.setText(username);
txtpassword.setText(password);
}
}
}
注意:第一次運行這個專案時,本地是沒有用戶名和密碼這個資料的,需要先輸入資料,最后點擊登錄,本地便會生成資料,
例:

本地記錄:

退出后再次打開這個軟體后,便會發現用戶名和密碼是顯示在上面的,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/211646.html
標籤:java
上一篇:自定義持久層框架
下一篇:iOS仿釘釘給界面或圖片添加水印
