Android学习(一)–用户登录注册界面(界面跳转+背景音乐)

目录

1.功能要求

2.功能实现流程图

3.功能演示

4.界面与功能

 4.1登录界面

4.1.1界面展示

4.1.2登录界面功能简介

4.1.3界面代码

4.1.4登录按钮点击事件

4.1.5退出按钮点击事件

 4.1.6背景音乐点击事件

4.1.7记住密码

5.Java源码


1.功能要求

(1)三个界面布局,体现文本框、编辑框、单选按钮、复选框按钮、按钮、listview控件,其它控件可自选。

(2)实现从第一个界面分别能跳转到另两个界面,其它两个界面也可返回第一个界面,将一个界面的数据通过Activity的数据传递传送到另一个界面。

(3)获取某个界面的数据,将数据存储到外部文件,数据存储方式可自选。

(4)根据各自项目的需求在某个界面中通过自定义广播、Toast提示实现一条广播的发送。

(5)在第一个界面当点击按钮时利用服务、MediaPlayer实现播放、停止播放背景音乐的功能。

2.功能实现流程图

3.功能演示

功能演示

4.界面与功能

 4.1登录界面

4.1.1界面展示

4.1.2登录界面功能简介

在登录界面可以实现5个功能:

(1)登录界面的跳转(2)注册界面的跳转(3)退出功能

(4)记住密码功能(5)背景音乐播放和停止功能

界面跳转功能我使用的是intent实现activity与activity之间的跳转,可以直接按返回键返回到前一页,不需要自己添加按键监听代码实现,但需要在manifest注册activity。

4.1.3界面代码

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bj1"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="75dp"
        android:layout_marginEnd="32dp"
        android:hint="请输入用户名"
        app:layout_constraintBottom_toTopOf="@+id/pwd"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        android:maxLines="1"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.972" />

    <EditText
        android:id="@+id/pwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="75dp"
        android:layout_marginEnd="32dp"
        android:hint="请输入密码"
        android:inputType="textPassword"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        android:maxLines="1"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.546" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="16dp"
        android:text="用户登录"
        android:textSize="28sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.89" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:text="用户:"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/pwd"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/name"
        app:layout_constraintVertical_bias="0.37" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:text="密码:"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="@+id/pwd"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        app:layout_constraintVertical_bias="0.718" />

    <Button
        android:id="@+id/login"
        style="@style/AlertDialog.AppCompat.Light"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="32dp"
        android:layout_marginRight="30dp"
        android:backgroundTint="@android:color/holo_blue_dark"
        android:text="登录"
        app:layout_constraintEnd_toStartOf="@+id/quit"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/pwd" />

    <Button
        android:id="@+id/reg"
        style="@style/AlertDialog.AppCompat.Light"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="76dp"
        android:layout_marginRight="30dp"
        android:backgroundTint="@android:color/holo_blue_dark"
        android:text="注册"
        app:layout_constraintEnd_toStartOf="@+id/quit"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/pwd" />

    <Button
        android:id="@+id/quit"
        style="@style/AlertDialog.AppCompat.Light"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginStart="30dp"
        android:layout_marginTop="120dp"
        android:layout_marginEnd="30dp"
        android:backgroundTint="@android:color/darker_gray"
        android:text="退出"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/pwd" />

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="5dp"
        android:text="记住密码"
        app:layout_constraintStart_toStartOf="@+id/login"
        app:layout_constraintTop_toBottomOf="@+id/pwd" />

    <ImageButton
        android:id="@+id/imagbutton"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="#00FF0000"
        android:onClick="onclickPlay"
        android:scaleType="centerInside"
        android:src="@drawable/bf" />

</androidx.constraintlayout.widget.ConstraintLayout>

4.1.4登录按钮点击事件

实现按钮的点击事件,在java代码中使用的是匿名内部类,给Button绑定一个监听事件,并监听一个点击事件,在setOnClickListener方法中直接传入一个OnClickListener对象,并实现OnClick方法。
点击登录按钮,如果用户编辑框的数据跟密码编辑框的数据相对应,就会跳转到欢迎界面;如果数据不对应,将会有toast弹窗提示“密码错误或用户不存在!”,如下图。

java代码实现

//登录事件
btnlogin.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String username = name.getText().toString();
        String password = pwd.getText().toString();       //获取用户输入的用户名和密码
        //查询用户名和密码相同的数据
        Cursor cursor = db.query("logins",new String[]{"usname","uspwd"}," usname=? and uspwd=?",new String[]{username,password},null,null,null);

        int flag = cursor.getCount();                   //查询出来的记录项的条数,若没有该用户则为0条
        if(flag!=0){                                    //若查询出的记录不为0,则进行跳转操作
            Intent intent = new Intent();
            intent.setClass(MainActivity.this,Welcome.class);            //设置页面跳转
            SharedPreferences.Editor editor = sp2.edit();
            cursor.moveToFirst();                                   //将光标移动到position为0的位置,默认位置为-1
            String loginname = cursor.getString(0);
            editor.putString("Loginname",loginname);
            editor.commit();                                        //将用户名存到SharedPreferences中
            startActivity(intent);
        }
        else{
            Toast.makeText(MainActivity.this,"密码错误或用户不存在!",Toast.LENGTH_LONG).show();             //提示用户信息错误或没有账号
        }

    }
});

4.1.5退出按钮点击事件

退出事件可由两种方式实现:

  1. 点击退出按钮退出,会有弹框弹出来提示用户是否退出程序。
  2. 返回键退出,在两秒内点击返回键实现退出程序。

如下图

 java代码实现

//退出事件
    back.setOnClickListener(new View.OnClickListener() {     //为退出按钮添加监听事件实现退出(用到弹框提示确认退出)
        @Override
        public void onClick(View v) {
            //创建弹框对象,显示在当前页面
            AlertDialog.Builder ab = new AlertDialog.Builder(MainActivity.this);
            //编辑弹框样式
            ab.setTitle("提示");                   //创建标题
            ab.setIcon(R.mipmap.ic_launcher_round);   //设置图标
            ab.setMessage("您是否确定退出?");         //设置内容
            //设置按钮
            ab.setPositiveButton("取消",null);
            ab.setNeutralButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // 实现程序的退出,结束当前
                    MainActivity.this.finish();
                }
            });
            //创建弹框
            ab.create();
            //显示弹框
            ab.show();
        }
    });
}

//2秒内点击两次返回键退出
long exittime;    //设定退出时间间隔
public boolean onKeyDown(int keyCode, KeyEvent event){   //参数:按的键;按键事件
    //判断事件触发
    if (keyCode == KeyEvent.KEYCODE_BACK){
        //判断两次点击间隔时间
        if((System.currentTimeMillis()-exittime)>2000){
            Toast.makeText(MainActivity.this,"再次返回程序退出!",Toast.LENGTH_SHORT).show();
            exittime = System.currentTimeMillis();    //设置第一次点击时间
        }else{
            finish();
            System.exit(0);
        }
        return true;
    }
    return super.onKeyDown(keyCode,event);

 4.1.6背景音乐点击事件

背景音乐的播放和暂停功能,这里使用的是soundpool实现背景音乐播放功能,soundpool类可用于管理和播放应用中的音频资源,这些音频资源可以放在存储文件中也可以包含在程序中,但实现播放的时间比较短。在这儿之前还需在res路径下新建一个raw的文件夹,并将提前准备好的mp3存放在此,如下图。

 java代码实现

//背景音乐
public void playSound(int sound, int loop) {    //获取AudioManager引用
    AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
    //获取当前音量
    float streamVolumeCurrent = am.getStreamVolume(AudioManager.STREAM_MUSIC);
    //获取系统最大音量
    float streamVolumeMax = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    //计算得到播放音量
    float volume = streamVolumeCurrent / streamVolumeMax;
    //调用SoundPool的play方法来播放声音文件
    currStaeamId = ms.play(music.get(sound), volume, volume, 1, loop, 1.0f);
}

public void initSoundPool() {//初始化声音池
    ms = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);  //创建SoundPool对象
    music = new HashMap<Integer, Integer>();   //创建HashMap对象
    //加载声音文件,并且设置为1号声音放入hm中
    music.put(1, ms.load(this, R.raw.bjmusic, 1));
}

public void onclickPlay(View view){
    //点击按钮播放音乐,再次点击停止播放
    if(cnt==0){
        cnt = 1;
    }
    else {
        cnt = 0;
    }
    if(cnt==1) {
        playSound(1,0);    //播放1号声音资源,且播放一次
        //提示播放
        Toast.makeText(MainActivity.this, "播放音效", Toast.LENGTH_SHORT).show();
    }
    else {
        ms.stop(currStaeamId);     //停止正在播放的声音
        //提示停止播放
        Toast.makeText(MainActivity.this, "停止播放音效", Toast.LENGTH_SHORT).show();
    }
}

4.1.7记住密码

使用sharedPreferencers方法实现记住密码功能,在登录界面输入内容后,勾选记住密码复选框,然后再点击登录,登录成功后将软件关掉,再重新打开,就会看到账号和密码就已经输入在框内了,记住的密码将会保存在Device File Explorer视图下的data/data/com.example.test06/shared_prefs文件中,如下图。

 java代码实现

//从SharedPreferences中获取是否记住密码的参数
final SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(this);
boolean isRemember = preference.getBoolean("remember_pwd", false);
//设置账号与密码到文本框,并勾选记住密码
if (isRemember) {
    name.setText(preference.getString("name", ""));
    pwd.setText(preference.getString("password", ""));
    remember_pwd.setChecked(true);
}

5.Java源码

package com.example.test06;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {
    EditText name,pwd;
    Button btnlogin,btnreg,back;
    CheckBox remember_pwd,show,editText;
    Mysql mysql;
    SQLiteDatabase db;
    SharedPreferences sp1,sp2;
    ImageButton btn_play;
    public static int cnt = 0;
    SoundPool ms;        //声明SoundPool的引用
    HashMap<Integer, Integer> music;      //声明HashMap来存放声音文件
    int currStaeamId;          //当前正播放的streamId

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = this.findViewById(R.id.name);            //用户名输入框
        pwd = this.findViewById(R.id.pwd);              //密码输入框
        btnlogin = this.findViewById(R.id.login);         //登录按钮
        btnreg = this.findViewById(R.id.reg);            //注册按钮
        back = this.findViewById(R.id.quit);             //退出按钮
        btn_play = this.findViewById(R.id.imagbutton);    //背景音乐按钮
        remember_pwd = this.findViewById(R.id.checkBox);    //复选按钮
        sp1 =  this.getSharedPreferences("useinfo",this.MODE_PRIVATE);
        sp2 = this.getSharedPreferences("username",this.MODE_PRIVATE);
        initSoundPool();//初始化声音池的方法

        name.setText(sp1.getString("usname",null));
        pwd.setText(sp1.getString("uspwd",null));
        mysql = new Mysql(this,"Userinfo",null,1);      //建立数据库
        db = mysql.getReadableDatabase();

        //从SharedPreferences中获取是否记住密码的参数
        final SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(this);
        boolean isRemember = preference.getBoolean("remember_pwd", false);
        //设置账号与密码到文本框,并勾选记住密码
        if (isRemember) {
            name.setText(preference.getString("name", ""));
            pwd.setText(preference.getString("password", ""));
            remember_pwd.setChecked(true);
        }

        //登录事件
        btnlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = name.getText().toString();
                String password = pwd.getText().toString();          //获取用户输入的用户名和密码
                //查询用户名和密码相同的数据
                Cursor cursor = db.query("logins",new String[]{"usname","uspwd"}," usname=? and uspwd=?",new String[]{username,password},null,null,null);

                int flag = cursor.getCount();                   //查询出来的记录项的条数,若没有该用户则为0条
                if(flag!=0){                                    //若查询出的记录不为0,则进行跳转操作
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this,Welcome.class);            //设置页面跳转
                    SharedPreferences.Editor editor = sp2.edit();
                    cursor.moveToFirst();                            //将光标移动到position为0的位置,默认位置为-1
                    String loginname = cursor.getString(0);
                    editor.putString("Loginname",loginname);
                    editor.commit();                                //将用户名存到SharedPreferences中
                    startActivity(intent);
                }
                else{
                    Toast.makeText(MainActivity.this,"密码错误或用户不存在!",Toast.LENGTH_LONG).show();             //提示用户信息错误或没有账号
                }

            }
        });

        //注册事件
        btnreg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,Register.class);      //跳转到注册页面
                startActivity(intent);
                Toast.makeText(MainActivity.this,"前往注册!",Toast.LENGTH_SHORT).show();
            }
        });

        //退出事件
        back.setOnClickListener(new View.OnClickListener() {     //为退出按钮添加监听事件实现退出(用到弹框提示确认退出)
            @Override
            public void onClick(View v) {
                //创建弹框对象,显示在当前页面
                AlertDialog.Builder ab = new AlertDialog.Builder(MainActivity.this);
                //编辑弹框样式
                ab.setTitle("提示");                   //创建标题
                ab.setIcon(R.mipmap.ic_launcher_round);   //设置图标
                ab.setMessage("您是否确定退出?");         //设置内容
                //设置按钮
                ab.setPositiveButton("取消",null);
                ab.setNeutralButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 实现程序的退出,结束当前
                        MainActivity.this.finish();
                    }
                });
                //创建弹框
                ab.create();
                //显示弹框
                ab.show();
            }
        });
    }

    //2秒内点击两次返回键退出
    long exittime;    //设定退出时间间隔
    public boolean onKeyDown(int keyCode, KeyEvent event){   //参数:按的键;按键事件
        //判断事件触发
        if (keyCode == KeyEvent.KEYCODE_BACK){
            //判断两次点击间隔时间
            if((System.currentTimeMillis()-exittime)>2000){
                Toast.makeText(MainActivity.this,"再次返回程序退出!",Toast.LENGTH_SHORT).show();
                exittime = System.currentTimeMillis();    //设置第一次点击时间
            }else{
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode,event);
    }

        //背景音乐
        public void playSound(int sound, int loop) {    //获取AudioManager引用
            AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
            //获取当前音量
            float streamVolumeCurrent = am.getStreamVolume(AudioManager.STREAM_MUSIC);
            //获取系统最大音量
            float streamVolumeMax = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            //计算得到播放音量
            float volume = streamVolumeCurrent / streamVolumeMax;
            //调用SoundPool的play方法来播放声音文件
            currStaeamId = ms.play(music.get(sound), volume, volume, 1, loop, 1.0f);
        }

        public void initSoundPool() {//初始化声音池
            ms = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);  //创建SoundPool对象
            music = new HashMap<Integer, Integer>();   //创建HashMap对象
            //加载声音文件,并且设置为1号声音放入hm中
            music.put(1, ms.load(this, R.raw.bjmusic, 1));
        }

        public void onclickPlay(View view){
            //点击按钮播放音乐,再次点击停止播放
            if(cnt==0){
                cnt = 1;
            }
            else {
                cnt = 0;
            }
            if(cnt==1) {
                playSound(1,0);    //播放1号声音资源,且播放一次
                //提示播放
                Toast.makeText(MainActivity.this, "播放音效", Toast.LENGTH_SHORT).show();
            }
            else {
                ms.stop(currStaeamId);     //停止正在播放的声音
                //提示停止播放
                Toast.makeText(MainActivity.this, "停止播放音效", Toast.LENGTH_SHORT).show();
            }
        }
}

未完待续

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇

)">
下一篇>>