登录界面 作业

布局页面

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout
 3     xmlns:android="http://schemas.android.com/apk/res/android"
 4     xmlns:tools="http://schemas.android.com/tools"
 5     android:layout_width="match_parent"
 6     android:layout_height="match_parent"
 7     tools:context="com.example.administrator.testapp3.Main2Activity"
 8     android:orientation="vertical">
 9 
10     <EditText
11         android:layout_width="match_parent"
12         android:layout_height="wrap_content"
13         android:hint="用户名"
14         android:id="@+id/yh"/>
15     <EditText
16         android:layout_width="match_parent"
17         android:layout_height="wrap_content"
18         android:hint="密码"
19         android:id="@+id/mm"/>
20     <Button
21         android:layout_width="match_parent"
22         android:layout_height="wrap_content"
23         android:text="登录"
24         android:onClick="bt2_onclick"/>
25 </LinearLayout>

 

 1 package com.example.administrator.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 Main2Activity extends AppCompatActivity {
11     EditText yh,mm; //定义
12 
13     @Override
14     protected void onCreate(Bundle savedInstanceState) {
15         super.onCreate(savedInstanceState);
16         setContentView(R.layout.activity_main2);
17 
18         yh = (EditText)findViewById(R.id.yh);
19         mm = (EditText)findViewById(R.id.mm); //声明
20 
21         //得到sharedpreferences对象(私有)
22         SharedPreferences sharedPreferences = getSharedPreferences("用户名",MODE_PRIVATE);
23         //读取Value
24         String str = sharedPreferences.getString("用户名",null);
25 
26         yh.setText(str);
27     }
28     public void bt2_onclick(View v)
29     {
30         yh = (EditText)findViewById(R.id.yh);
31         mm = (EditText)findViewById(R.id.mm);//声明
32 
33         String a=yh.getText().toString();
34         String b=mm.getText().toString();
35         //判断用户名长度
36         if (a==null||a.trim().length()==0||b==null||b.trim().length()==0)
37         {
38             //如果长度为空和为0时,返回输入信息提示
39             Toast.makeText(Main2Activity.this, "请正确输入用户名或密码", Toast.LENGTH_SHORT).show();
40         }
41         else //否则
42         {
43             //得到sharedpreferences对象(追加)
44             SharedPreferences sp = getSharedPreferences("用户名",MODE_APPEND);
45             //得到编辑器
46             SharedPreferences.Editor ed = sp.edit();
47             //使用editor添加数据
48             ed.putString("用户名",a);
49             //保存数据
50             ed.commit();
51             //如果用户名和密码输入正确 提示正确登录信息
52             Toast.makeText(Main2Activity.this, "登录成功", Toast.LENGTH_SHORT).show();
53         }
54     }
55 }

posted @ 2016-05-23 19:47  宫崎天川  阅读(241)  评论(0编辑  收藏  举报