【Android Studio】安卓APP期末作品记录之一个Activity中两个fragment间的切换以及使用sqlite数据库实现登录/注册功能

1,634 阅读4分钟

前情提要

如果感兴趣的话,可以到GitHub上下载我的完整作品源代码:github.com

这是我期末作品的第一个界面,点击注册切换到注册界面,点击返回登陆切换到登录界面。使用sqlite数据库实现登录/注册功能。

Screenshot_20230623_215939.png Screenshot_20230623_220038.png

一个Activity中两个fragment间的切换问题

主要使用FragmentManager和FragmentTransaction

先放上界面的布局文件,activity_login_or_register.xmlfragment_register.xmlfragment_login.xml

activity_login_or_register.xml:

<?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:background="@color/background"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/startBanner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="@color/black"
        android:textSize="40dp"
        android:padding="5dp"
        android:text="登录界面" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/loginOrRegisterFragment"
        >

    </FrameLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/startUILogin"
        android:gravity="center"
        android:padding="15dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/loginButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="15dp"
            android:background="@drawable/button"
            android:padding="5dp"
            android:textColor="@color/background"
            android:text="登录"
            android:textSize="20sp" />

        <Button
            android:id="@+id/registerButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:background="@drawable/button"
            android:textColor="@color/background"
            android:padding="5dp"
            android:textSize="20sp"
            android:text="注册" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/startUIRegister"
        android:padding="15dp"
        android:gravity="center"
        android:visibility="gone"
        android:orientation="horizontal">

        <Button
            android:id="@+id/nowRegisterButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="15dp"
            android:background="@drawable/button"
            android:padding="5dp"
            android:textColor="@color/background"
            android:textSize="20sp"
            android:text="立刻注册" />

        <Button
            android:id="@+id/returnLoginButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:background="@drawable/button"
            android:textColor="@color/background"
            android:padding="5dp"
            android:textSize="20sp"
            android:text="返回登录" />
    </LinearLayout>
</LinearLayout>

fragment_register.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <EditText
        android:id="@+id/registerUsername"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:background="@drawable/border"
        android:layout_margin="10dp"
        android:padding="10dp"
        android:hint="用户名"/>
    <EditText
        android:id="@+id/registerPassword"
        android:layout_width="fill_parent"
        android:layout_height="60dp"
        android:textSize="20sp"
        android:background="@drawable/border"
        android:layout_margin="10dp"
        android:padding="10dp"
        android:inputType="textPassword"
        android:hint="请输入密码"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginLeft="5dp"
        android:layout_gravity="center">

        <TextView
            android:id="@+id/ownSex"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="性别:"
            android:padding="5dp"
            android:layout_gravity="center"/>
        <RadioGroup
            android:id="@+id/registerRadioGroupSex"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/registerRadioMale"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="男"
                tools:ignore="TouchTargetSizeCheck" />

            <RadioButton
                android:id="@+id/registerRadioFemale"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="女"
                tools:ignore="TouchTargetSizeCheck" />
        </RadioGroup>
    </LinearLayout>
</LinearLayout>

fragment_login.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="登录" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_margin="20dp">

        <EditText
            android:id="@+id/loginUsername"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:background="@drawable/border"
            android:hint="名称"
            android:padding="10dp"
            tools:ignore="TouchTargetSizeCheck" />

        <EditText
            android:id="@+id/loginPassword"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:background="@drawable/border"
            android:hint="密码"
            android:padding="10dp"
            android:inputType="textPassword"
            tools:ignore="TouchTargetSizeCheck" />

    </LinearLayout>
</LinearLayout>

接下来就可以开始写切换fragment的代码了。 LoginOrRegisterActivity.java:

public class LoginOrRegisterActivity extends AppCompatActivity {
    private FragmentManager manager;
    private FragmentTransaction transaction;
    private Fragment currentFragment;

    public LoginFragment loginFragment = new LoginFragment();
    public RegisterFragment registerFragment = new RegisterFragment();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//去除标题
        setContentView(R.layout.activity_login_or_register);

        //初始化fragments
        manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();
        transaction.add(R.id.loginOrRegisterFragment, loginFragment);
        transaction.show(loginFragment);
        transaction.hide(registerFragment);
        transaction.commit();
        currentFragment=loginFragment;

    // fragments之间的切换
    public void FragmentHideShow(Fragment fg) {
        manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();
        if (!fg.isAdded()) {
            transaction.hide(currentFragment);
            transaction.add(R.id.loginOrRegisterFragment, fg);
            transaction.show(fg);
        } else {
            transaction.hide(currentFragment);
            transaction.show(fg);
        }
        currentFragment = fg;
        transaction.commit();
    }
}

执行切换fragment的代码是在注册返回登陆这两个按钮中,所以我就写在LoginFragment.javaRegisterFragment.java中了。

只要在需要切换的地方写下这一行代码就可以了

FragmentHideShow(loginFragment);

因为我是在fragment中调用activity的函数,所以我是这样写的:

((LoginOrRegisterActivity)getActivity()).FragmentHideShow(loginFragment);

登录/注册功能实现

完整代码在文末

登录功能

登录功能设计思路流程图:

登录.jpg

注册功能

注册功能设计思路流程图:

注册.jpg

完整代码

因为这个涉及到数据库还有我的期末作品要求涉及到activity与fragment之间的数据传递问题,我的登录按钮是写在LoginOrRegisterActivity.java中的~~(懒得改了)~~,所以这里只放出LoginOrRegisterActivity.javaRegisterFragment.javaLoginFragment.java的完整代码,仅供参考,用户的匹配问题还有数据库的操作还需根据自己的要求来。

如果感兴趣的话,可以到GitHub上下载我的作品源代码:github.com

LoginOrRegisterActivity.java:

public class LoginOrRegisterActivity extends AppCompatActivity {
    private Button loginBtn;
    public TextView bannerText;
    private EditText loginUsername;
    private EditText loginPassword;

    private FragmentManager manager;
    private FragmentTransaction transaction;
    private Fragment currentFragment;

    public LoginFragment loginFragment = new LoginFragment();
    public RegisterFragment registerFragment = new RegisterFragment();

    private LinearLayout loginLinearLayout;
    private LinearLayout registerLinearLayout;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//去除标题
        setContentView(R.layout.activity_login_or_register);

        openDatabase();

        InitFragment initFragment = new InitFragment();
        initFragment.init();
        Page5Fragment page5Fragment = initFragment.getPage5();

        //初始化fragments
        manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();
        transaction.add(R.id.loginOrRegisterFragment, loginFragment);
        transaction.show(loginFragment);
        transaction.hide(registerFragment);
        transaction.commit();
        currentFragment=loginFragment;

        loginLinearLayout = (LinearLayout) findViewById(R.id.startUILogin);
        registerLinearLayout = (LinearLayout) findViewById(R.id.startUIRegister);
        bannerText = (TextView) findViewById(R.id.startBanner);
        loginBtn = (Button) findViewById(R.id.loginButton);

        loginBtn.setOnClickListener((new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loginUsername = (EditText) manager.findFragmentById(R.id.loginOrRegisterFragment).getView().findViewById(R.id.loginUsername);
                loginPassword = (EditText) manager.findFragmentById(R.id.loginOrRegisterFragment).getView().findViewById(R.id.loginPassword);

                String name = loginUsername.getText().toString();

                // 获取用户是否存在的布尔值
                String password = loginPassword.getText().toString();
                String sql = "select * from users where username=? and password=?";
                String[] o = new String[]{name,password};
                GetSQLite getSQLite=new GetSQLite();
                boolean ifExist = getSQLite.ifUserExist(LoginOrRegisterActivity.this, sql, o);

                // 判断用户是否存在
                if(ifExist){
                    Intent intent = new Intent(LoginOrRegisterActivity.this, MainActivity.class);
                    String[] s = new String[]{name,password};
                    User user = getSQLite.getUser(LoginOrRegisterActivity.this, s);

                    // 数据传递
                    intent.putExtra("account",user.getAccount());
                    intent.putExtra("username",name);
                    intent.putExtra("password",password);
                    intent.putExtra("sex",user.getSex());

                    startActivity(intent);
                }
                else{
                    Toast toast=Toast.makeText(LoginOrRegisterActivity.this, "用户名或密码不正确!", Toast.LENGTH_SHORT);
                    toast.show();
                }
            }
        }));
    }

// fragments之间的切换
    public void FragmentHideShow(Fragment fg) {
        manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();
        if (!fg.isAdded()) {
            transaction.hide(currentFragment);
            transaction.add(R.id.loginOrRegisterFragment, fg);
            transaction.show(fg);
        } else {
            transaction.hide(currentFragment);
            transaction.show(fg);
        }
        currentFragment = fg;
        transaction.commit();
    }

    public void openDatabase(){
        MyDatabaseHelper myHelper = new MyDatabaseHelper(LoginOrRegisterActivity.this);
        try {
            myHelper.CopyDBFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

RegisterFragment.java:

package com.example.app.fragment;

import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.app.LoginOrRegisterActivity;
import com.example.app.R;
import com.example.app.util.GetSQLite;

import java.util.UUID;

public class RegisterFragment extends Fragment {
    private Button nowRegisterBtn;
    private Button returnLoginBtn;

    private TextView bannerText;

    private EditText registerUsername;
    private EditText registerPassword;

    RadioButton radioMale;
    RadioButton radioFemale;
    RadioGroup radioGroup;

    private LinearLayout loginLinearLayout;
    private LinearLayout registerLinearLayout;

    public LoginFragment loginFragment;
//    public RegisterFragment registerFragment = new RegisterFragment();

    private String sex;


    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_register, container, false);

        nowRegisterBtn = (Button) ((LoginOrRegisterActivity)getActivity()).findViewById(R.id.nowRegisterButton);
        returnLoginBtn = (Button) ((LoginOrRegisterActivity)getActivity()).findViewById(R.id.returnLoginButton);
        loginLinearLayout = (LinearLayout) ((LoginOrRegisterActivity)getActivity()).findViewById(R.id.startUILogin);
        registerLinearLayout = (LinearLayout) ((LoginOrRegisterActivity)getActivity()).findViewById(R.id.startUIRegister);
        bannerText = (TextView) ((LoginOrRegisterActivity)getActivity()).findViewById(R.id.startBanner);
        registerUsername = (EditText) view.findViewById(R.id.registerUsername);
        registerPassword = (EditText) view.findViewById(R.id.registerPassword);
        radioMale = (RadioButton) view.findViewById(R.id.registerRadioMale);
        radioFemale = (RadioButton) view.findViewById(R.id.registerRadioFemale);
        radioGroup = (RadioGroup) view.findViewById(R.id.registerRadioGroupSex);

        loginFragment = new LoginFragment();

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton rb = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
                sex = rb.getText().toString();
            }
        });

        nowRegisterBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = registerUsername.getText().toString();
                String password = registerPassword.getText().toString();
                GetSQLite getSQLite=new GetSQLite();

                String checkSql = "select * from users where username=?";
                String[] checkO = new String[]{name};
                boolean ifExist = getSQLite.ifUserExist(getActivity(), checkSql, checkO);
                if(ifExist){
                    registerUsername.setText("");
                    registerPassword.setText("");
                    Toast toast=Toast.makeText(getActivity(), "此账户名已被占用!", Toast.LENGTH_SHORT);
                    toast.show();
                }
                else{
                    String account = CreateId();
                    String sql = "insert into users values(?,?,?,?)";
                    Object[] o = new Object[]{account,name,sex,password};
                    getSQLite.insertData(getActivity(), sql, o);
                    Toast toast=Toast.makeText(getActivity(), "注册成功!", Toast.LENGTH_SHORT);
                    toast.show();
                    bannerText.setText("登录界面");
                    ((LoginOrRegisterActivity)getActivity()).FragmentHideShow(loginFragment);
                    loginLinearLayout.setVisibility(View.VISIBLE);
                    registerLinearLayout.setVisibility(View.GONE);
                }

            }
        });

        returnLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ((LoginOrRegisterActivity)getActivity()).FragmentHideShow(loginFragment);
                loginLinearLayout.setVisibility(View.VISIBLE);
                registerLinearLayout.setVisibility(View.GONE);
                bannerText.setText("登录界面");
            }
        });

        return view;
    }
    // 创建八位账号ID
    private String CreateId(){
        String[] c = new String[] { "a", "b", "c", "d", "e", "f",
                "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
                "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
                "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
                "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z" };

        StringBuffer shortBuffer = new StringBuffer();
        System.out.println("原来生成的36位uuid");
        String uuid = UUID.randomUUID().toString();
        System.out.println(uuid);

        uuid=uuid.replace("-", "");
        System.out.println("替换-后的32位uuid");
        System.out.println(uuid);

        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(c[x % 62]);
        }
        String str = shortBuffer.toString();

        System.out.println("生成的随机字符"+str);

        return str;
    }

}

LoginFragment.java:

public class LoginFragment extends Fragment {
    private Button registerBtn;
    private TextView bannerText;

    private LinearLayout loginLinearLayout;
    private LinearLayout registerLinearLayout;

    public LoginFragment loginFragment;
    public RegisterFragment registerFragment;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login, container, false);

        registerBtn = (Button) ((LoginOrRegisterActivity)getActivity()).findViewById(R.id.registerButton);
        loginLinearLayout = (LinearLayout) ((LoginOrRegisterActivity)getActivity()).findViewById(R.id.startUILogin);
        registerLinearLayout = (LinearLayout) ((LoginOrRegisterActivity)getActivity()).findViewById(R.id.startUIRegister);
        bannerText = (TextView) ((LoginOrRegisterActivity)getActivity()).findViewById(R.id.startBanner);
        registerFragment = new RegisterFragment();
        loginFragment = new LoginFragment();

        registerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((LoginOrRegisterActivity)getActivity()).FragmentHideShow(registerFragment);
                registerLinearLayout.setVisibility(View.VISIBLE);
                loginLinearLayout.setVisibility(View.GONE);
                bannerText.setText("注册界面");
            }
        });

        return view;
    }
}