桃词典 Peach Dictionary 简易英语词典app开发 安卓软件开发 Part 4

190 阅读4分钟

前文: 桃词典 Peach Dictionary 简易英语词典app开发 安卓软件开发 Part 3 导航:

桃词典 Peach Dictionary 简易英语词典app开发 安卓软件开发 The End 导航页及收尾工作

2.实现注册功能

(1)新建一个用于注册的empty activity。

(2)搭建注册界面的UI布局。

activity_register.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="schemas.android.com/apk/res/and…" xmlns:app="schemas.android.com/apk/res-aut…" xmlns:tools="schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".register">

<ImageButton
    android:id="@+id/imageButton2"
    android:layout_width="65dp"
    android:layout_height="66dp"
    android:backgroundTint="#00FFFFFF"
    android:contentDescription="@string/TODO"
    android:minHeight="48dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.004"
    app:srcCompat="@drawable/ic_baseline_navigate_before_24" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/textview1"
    android:textAlignment="center"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1"
    android:textSize="30sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@+id/guideline3"
    app:layout_constraintVertical_bias="0.153" />

<androidx.constraintlayout.widget.Guideline
    android:id="@+id/guideline3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.1" />

<EditText
    android:id="@+id/editTextTextPersonName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="60dp"
    android:ems="10"
    android:hint="@string/Username"
    android:inputType="textPersonName"
    android:minHeight="48dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.497"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@+id/guideline3"
    app:layout_constraintVertical_bias="0.26" />

<EditText
    android:id="@+id/editTextTextPassword2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="@string/Password"
    android:inputType="textPassword"
    android:minHeight="48dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.497"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/editTextTextPersonName"
    app:layout_constraintVertical_bias="0.085" />

<EditText
    android:id="@+id/editTextNumberPassword"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="@string/RePassword"
    android:inputType="numberPassword"
    android:minHeight="48dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.497"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/editTextTextPassword2"
    app:layout_constraintVertical_bias="0.114" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/textview2"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1"
    android:textSize="34sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toTopOf="@+id/textView2"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@+id/guideline3"
    app:layout_constraintVertical_bias="0.23" />

<ImageButton
    android:id="@+id/imageButton3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:backgroundTint="#00FFFFFF"
    android:contentDescription="@string/TODO"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.498"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/editTextNumberPassword"
    app:layout_constraintVertical_bias="0.158"
    app:srcCompat="@drawable/ic_baseline_send_24" />

</androidx.constraintlayout.widget.ConstraintLayout>

使用图片均为android studio自带的矢量图,这里用到的有:

@drawable/ic_baseline_navigate_before_24 @drawable/ic_baseline_send_24 (3)使用SharedPreference实现注册功能,使用MD5加密密码。

register.java

package com.example.peachdictionary;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast;

import java.security.MessageDigest;

public class register extends AppCompatActivity { private ImageButton btn_login;//登录按钮

//用户名,密码,再次输入的密码的控件
private EditText et_user_name,et_psw,et_psw_again;

//用户名,密码,再次输入的密码的控件的获取值
private String userName,psw,pswAgain;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    //设置此界面为竖屏
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
    init();
}



private void init(){
    //控件初始化
    ImageButton imageButton2 = findViewById(R.id.imageButton2);
    btn_login = findViewById(R.id.imageButton3);
    et_user_name = findViewById(R.id.editTextTextPersonName);
    et_psw = findViewById(R.id.editTextTextPassword2);
    et_psw_again = findViewById(R.id.editTextNumberPassword);

    //返回键
    imageButton2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(register.this,MainActivity.class);
            startActivity(intent);
        }
    });

    //注册按钮
    btn_login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //获取输入在相应控件中的字符串
            getEditString();
            //判断输入框内容
            if (TextUtils.isEmpty(userName)) {
                Toast.makeText(register.this, "请输入用户名", Toast.LENGTH_SHORT).show();
                return;
            } else if (TextUtils.isEmpty(psw)) {
                Toast.makeText(register.this, "请输入密码", Toast.LENGTH_SHORT).show();
                return;
            } else if (TextUtils.isEmpty(pswAgain)) {
                Toast.makeText(register.this, "请再次输入密码", Toast.LENGTH_SHORT).show();
                return;
            } else if (!psw.equals(pswAgain)) {
                Toast.makeText(register.this, "输入两次的密码不一样", Toast.LENGTH_SHORT).show();
                return;
                /**
                 *从SharedPreferences中读取输入的用户名,判断SharedPreferences中是否有此用户名
                 */
            } else if (isExistUserName(userName)) {
                Toast.makeText(register.this, "此账户名已经存在", Toast.LENGTH_SHORT).show();
                return;
            } else {
                Toast.makeText(register.this, "注册成功", Toast.LENGTH_SHORT).show();
                //把账号、密码和账号标识保存到sp里面
                /**
                 * 保存账号和密码到SharedPreferences中
                 */
                saveRegisterInfo(userName, psw);
                //注册成功后把账号传递到LoginActivity.java中
                // 返回值到loginActivity显示
                Intent data = new Intent();
                data.putExtra("userName", userName);
                setResult(RESULT_OK, data);
                //RESULT_OK为Activity系统常量,状态码为-1,
                // 表示此页面下的内容操作成功将data返回到上一页面,如果是用back返回过去的则不存在用setResult传递data值
                register.this.finish();

            }
        }
    });
}


/**
 * 获取控件中的字符串
 */
private void getEditString(){
    userName=et_user_name.getText().toString().trim();
    psw=et_psw.getText().toString().trim();
    pswAgain=et_psw_again.getText().toString().trim();
}

/**
 * 从SharedPreferences中读取输入的用户名,判断SharedPreferences中是否有此用户名
 */
private boolean isExistUserName(String userName){
    boolean has_userName=false;
    //mode_private SharedPreferences sp = getSharedPreferences( );
    // "loginInfo", MODE_PRIVATE
    SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
    //获取密码
    String spPsw=sp.getString(userName, "");//传入用户名获取密码
    //如果密码不为空则确实保存过这个用户名
    if(!TextUtils.isEmpty(spPsw)) {
        has_userName=true;
    }
    return has_userName;
}
/**
 * 保存账号和密码到SharedPreferences中SharedPreferences
 */
private void saveRegisterInfo(String userName,String psw){
    String md5Psw = MD5Util.encrypt(psw);//把密码用MD5加密
    //loginInfo表示文件名, mode_private SharedPreferences sp = getSharedPreferences( );
    SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
    //获取编辑器, SharedPreferences.Editor  editor -> sp.edit();
    SharedPreferences.Editor editor=sp.edit();
    //以用户名为key,密码为value保存在SharedPreferences中
    //key,value,如键值对,editor.putString(用户名,密码);
    editor.putString(userName, md5Psw);
    //提交修改 editor.commit();
    editor.commit();
}


public static class MD5Util {
    private static final String TAG = "MD5Util";

    /***
     * MD5加码 生成32位md5码
     */
    public static String string2MD5(String inStr) {
        Log.e(TAG, "string2MD5: -------------------------");
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();

    }

    /**
     * 加密解密算法 执行一次加密,两次解密
     */
    public static String convertMD5(String inStr) {
        Log.e(TAG, "convertMD5: ----------------------------------------------------------");
        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String s = new String(a);
        return s;

    }

    //encrypt译成密码
    public static String encrypt(String str) {
        // MD5
        String s1 = string2MD5(str);
        //加密
        //String s1 = MD5(str);


        String s = new String(str);

        Log.e(TAG, "show: ------------原始:" + s);
        Log.e(TAG, "show: ------------MD5后:" + string2MD5(s));
        Log.e(TAG, "show: ------------加密的:" + convertMD5(s));
        Log.e(TAG, "show: ------------解密的:" + convertMD5(convertMD5(s)));
        // return convertMD5(convertMD5(s));
        //        return convertMD5(s);
        return string2MD5(s);

    }

    public String decode(String jiemi) {
        Log.e(TAG, "这是解密--------------*****---------" + convertMD5(jiemi));
        return convertMD5(jiemi);
    }

    public static String MD5(String sourceStr) {
        try {
            // 获得MD5摘要算法的 MessageDigest对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(sourceStr.getBytes());
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            StringBuffer buf = new StringBuffer();
            for (int i = 0; i < md.length; i++) {
                int tmp = md[i];
                if (tmp < 0)
                    tmp += 256;
                if (tmp < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(tmp));
            }
            //return buf.toString().substring(8, 24);// 16位加密
            return buf.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

}

(4)在Mainactivity使用Intent,使Mainactivity可以跳转到注册界面。

MainActivity.java

package com.example.peachdictionary;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent; import android.content.pm.ActivityInfo; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);

     //设置此界面为竖屏
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
     videobackground();

 }

 private void videobackground() {

     //视频背景
     final VideoView videoview = findViewById(R.id.video_background);
     final String videopath = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.background).toString();
     videoview.setVideoPath(videopath);
     videoview.start();
     videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
         @Override
         public void onPrepared(MediaPlayer mp) {
             mp.start();
             mp.setLooping(true);
         }
     });

     videoview.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
         @Override
         public void onCompletion(MediaPlayer mediaPlayer) {
             videoview.setVideoPath(videopath);
             videoview.start();
         }
     });

     Button button = findViewById(R.id.button);
     button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
             Intent intent = new Intent(MainActivity.this, register.class);
             startActivity(intent);
         }
     });


 }

}

实现效果:

———————————————— 版权声明:本文为CSDN博主「SEMHAQ」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:blog.csdn.net/weixin_6062…