SharedPreferences存储用户名

制作一个登录界面,以SP方式存储用户名。用户下次登录时自动显示上次填写的用户名
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     android:paddingBottom="@dimen/activity_vertical_margin"
 7     android:paddingLeft="@dimen/activity_horizontal_margin"
 8     android:paddingRight="@dimen/activity_horizontal_margin"
 9     android:paddingTop="@dimen/activity_vertical_margin"
10     tools:context="com.hanqi.testapp3.a"
11     android:orientation="vertical">
12 
13     <EditText
14         android:layout_width="match_parent"
15         android:layout_height="wrap_content"
16         android:hint="用户名"
17         android:id="@+id/et_yhm"/>
18 
19     <EditText
20         android:layout_width="match_parent"
21         android:layout_height="wrap_content"
22         android:hint="密码"
23         android:id="@+id/et_mm"/>
24 
25     <LinearLayout
26         android:layout_width="match_parent"
27         android:layout_height="wrap_content">
28         <Button
29             android:layout_width="0dp"
30             android:layout_height="wrap_content"
31             android:layout_weight="1"
32             android:text="登陆"
33             android:onClick="bt_denglu"/>
34         <Button
35             android:layout_width="0dp"
36             android:layout_height="wrap_content"
37             android:layout_weight="1"
38             android:text="注册"/>
39     </LinearLayout>
40 
41 
42 
43 </LinearLayout>
登录界面
 1 package com.hanqi.testapp3;
 2 
 3 import android.content.SharedPreferences;
 4 import android.support.v7.app.AppCompatActivity;
 5 import android.os.Bundle;
 6 import android.view.View;
 7 import android.widget.EditText;
 8 import android.widget.Toast;
 9 
10 public class a extends AppCompatActivity {
11 
12     EditText et_yhm;
13     EditText et_mm;
14 
15     @Override
16     protected void onCreate(Bundle savedInstanceState) {
17         super.onCreate(savedInstanceState);
18         setContentView(R.layout.activity_a);
19 
20         et_yhm = (EditText)findViewById(R.id.et_yhm);
21         et_mm = (EditText)findViewById(R.id.et_mm);
22 
23         SharedPreferences sp = getSharedPreferences("name",MODE_APPEND);
24 
25         String name = sp.getString("name",null);
26 
27         et_yhm.setText(name);
28     }
29 
30     public void bt_denglu(View v)
31     {
32         String yhm = et_yhm.getText().toString();
33 
34         SharedPreferences sharedPreferences = getSharedPreferences("name", MODE_APPEND);
35 
36         SharedPreferences.Editor editor = sharedPreferences.edit();
37 
38         editor.putString("name",yhm);
39 
40         editor.commit();
41 
42         Toast.makeText(a.this, "登陆成功", Toast.LENGTH_SHORT).show();
43     }
44 }
java代码
原文地址:https://www.cnblogs.com/future-zhenzhen/p/5522351.html