您的当前位置:首页正文

Android Studio 大作业--学生信息管理系统

2024-10-31 来源:个人技术集锦

 欢迎光临:


内容大概:

简易学生信息管理系统项目需求,大致需要以下Java文件和XML布局文件:

Java文件:

Student 类(实体类):用于存储学生信息。
StudentDBHelper 类(数据库操作类):继承自SQLiteOpenHelper,负责创建表、插入、删除、更新和查询学生数据。
StudentListAdapter 类(RecyclerView Adapter):适配器类,用于在“学生列表”模块展示学生数据。
StudentListFragment 类(Fragment):实现学生列表界面功能,包含RecyclerView及其Adapter的初始化等。
AddStudentFragment 类(Fragment):实现添加学生界面功能,包含EditText输入框、Button提交按钮、ImageView头像选择等。
SearchStudentFragment 类(Fragment):实现查询学生界面功能,包含EditText输入框、CheckBox或RadioButton查询条件选择、查询结果展示列表的初始化等。
SearchStudentListAdapter 类(RecyclerView Adapter):适配器类,用于在“搜索”模块展示学生数据。
MainActivity:用于初始化底部导航栏与ViewPager2,并管理各个Fragment。

XML布局文件:

activity_main.xml:主Activity布局文件,包含ViewPager2和TabLayout等控件。
fragment_student_list.xml:学生列表Fragment的布局文件,包含RecyclerView等控件。
fragment_add_student.xml:添加学生Fragment的布局文件,包含姓名、学号、专业等EditText输入框以及上传或选择图片的ImageView和提交按钮等控件。
item_student1.xml:RecyclerView中单个学生项的布局文件,包含显示学生信息的各种TextView、ImageView等控件。
fragment_search_student.xml:查询学生Fragment的布局文件,包含查询输入框、查询条件选择控件以及查询结果展示的ListView或RecyclerView控件。
item_student2.xml:RecyclerView中单个学生项的布局文件,包含显示学生信息的各种TextView、ImageView等控件。
dialog_delete_confirm.xml:删除确认AlertDialog或PopupWindow的布局文件,包含提示文字和确认/取消按钮。
bottom_navigation_menu.xml:底部导航栏。

 使用的控件:

此APP中包含以下控件:

Button、TextView、EditText、ImageView、Toast、Activity 跳转和传值、ViewPager2+Fragment 底部导航

PopupWindow & AlertDialog、数据库

RadioButton、CheckBox、返回值、RecyclerView

整体架构:


 示例展示:

学生列表

 添加

 搜索


源代码: 

JAVA代码

MainActivity

package com.example.myfinalwork;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.appcompat.widget.Toolbar;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.Menu;
import android.widget.Toast;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.example.myfinalwork.StudentListRefreshListener;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements StudentListRefreshListener {

    private ViewPager2 viewPager;
    private BottomNavigationView bottomNavigationView;
    private List<Fragment> fragmentsList;
    private MenuItem lastSelectedMenuItem;
    private StudentListFragment studentListFragment; // 新增变量

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

        // 初始化ViewPager2和BottomNavigationView
        viewPager = findViewById(R.id.view_pager);
        setupViewPager();

        // 在这里找到并保存StudentListFragment的引用
        for (Fragment fragment : fragmentsList) {
            if (fragment instanceof StudentListFragment) {
                studentListFragment = (StudentListFragment) fragment;
                break;
            }
        }

        bottomNavigationView = findViewById(R.id.bottom_navigation_view);
        bottomNavigationView.setOnNavigationItemSelectedListener(navigationItemSelectedListener());
        bottomNavigationView.setSelectedItemId(R.id.action_student_list);
    }

    @Override
    public void onStudentListRefresh() {
        if (studentListFragment != null) {
            studentListFragment.refreshStudentList();
        }
    }

    private BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener() {
        return new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                if (item.getItemId() == R.id.action_student_list) {
                    viewPager.setCurrentItem(0);
                } else if (item.getItemId() == R.id.action_add_student) {
                    viewPager.setCurrentItem(1);
                } else if (item.getItemId() == R.id.action_search_student) {
                    viewPager.setCurrentItem(2);
                }
                lastSelectedMenuItem = item;
                return true;
            }
        };
    }

    private void setupViewPager() {
        fragmentsList = new ArrayList<>();
        studentListFragment = new StudentListFragment(); // 修改:直接使用类级别的变量
        AddStudentFragment addStudentFragment = new AddStudentFragment();
        SearchStudentFragment searchStudentFragment = new SearchStudentFragment();

        // 为AddStudentFragment设置一个接口回调以通知MainActivity刷新列表
        addStudentFragment.setStudentListRefreshListener(this);

        fragmentsList.add(studentListFragment);
        fragmentsList.add(addStudentFragment);
        fragmentsList.add(searchStudentFragment);

        viewPager.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return fragmentsList.get(position);
            }

            @Override
            public int getItemCount() {
                return fragmentsList.size();
            }
        });
        viewPager.setUserInputEnabled(false); // 可选:禁用手动滑动切换页面
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.bottom_navigation_menu, menu);
        return true;
    }
}

 Student类

package com.example.myfinalwork;

public class Student {
    private String id;
    private String name;
    private String major;
    private boolean selected; // 添加一个布尔变量来表示学生是否被选中

    public Student(String id, String name, String major) {
        this.id = id;
        this.name = name;
        this.major = major;
        this.selected = false; // 初始化时默认未选中
    }

    public Student() {

    }

    // Getters and Setters
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    // 新增isSelected()和setSelected()方法
    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", major='" + major + '\'' +
                ", selected=" + selected +
                '}';
    }
}

 StudentDBHelper类

package com.example.myfinalwork;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class StudentDBHelper extends SQLiteOpenHelper {
    // 数据库名称
    private static final String DATABASE_NAME = "StudentManager.db";
    // 数据库版本号,每次更新数据库结构时需要增加
    private static final int DATABASE_VERSION = 1;

    // 学生信息表名
    public static final String TABLE_NAME_STUDENTS = "students";

    // 表列名定义
    public static final String COLUMN_ID = "id";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_MAJOR = "major";

    // 创建学生信息表的SQL语句
    private static final String CREATE_TABLE_STUDENTS = "CREATE TABLE " + TABLE_NAME_STUDENTS +
            "(" +
            COLUMN_ID + " TEXT PRIMARY KEY," +
            COLUMN_NAME + " TEXT NOT NULL," +
            COLUMN_MAJOR + " TEXT NOT NULL" +
            ")";

    public StudentDBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_STUDENTS);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 在数据库版本升级时,可以在此处添加数据迁移逻辑或者删除旧表重建新表
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_STUDENTS);
        onCreate(db);
    }

    /**
     * 一个简单的方法用于将学生信息插入数据库,具体实现由StudentDBHelper提供
     * @param student 要插入的学生对象
     */
    public void insertStudent(Student student) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_ID, student.getId());
        values.put(COLUMN_NAME, student.getName());
        values.put(COLUMN_MAJOR, student.getMajor());

        db.insert(TABLE_NAME_STUDENTS, null, values);
        db.close(); // 关闭数据库连接
    }

    /**
     * 根据查询条件搜索学生
     * @param query 搜索关键词
     * @param searchBy 搜索依据字段("name" 或 "id" 或 "major")
     * @return 匹配到的学生列表
     */
    public List<Student> searchStudents(String query, String searchBy) {
        List<Student> studentList = new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor;

        if (searchBy.equals("name")) {
            cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME_STUDENTS +
                    " WHERE " + COLUMN_NAME + " LIKE ?", new String[]{"%" + query + "%"});
        } else if (searchBy.equals("id")) {
            cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME_STUDENTS +
                    " WHERE " + COLUMN_ID + " LIKE ?", new String[]{"%" + query + "%"});
        } else if (searchBy.equals("major")) {
            cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME_STUDENTS +
                    " WHERE " + COLUMN_MAJOR + " LIKE ?", new String[]{"%" + query + "%"});
        } else {
            throw new IllegalArgumentException("Invalid searchBy field");
        }

        if (cursor.moveToFirst()) {
            do {
                Student student = new Student();
                int idColumnIndex = cursor.getColumnIndex(COLUMN_ID);
                int nameColumnIndex = cursor.getColumnIndex(COLUMN_NAME);
                int majorColumnIndex = cursor.getColumnIndex(COLUMN_MAJOR);

                if (idColumnIndex >= 0) {
                    student.setId(cursor.getString(idColumnIndex));
                }
                if (nameColumnIndex >= 0) {
                    student.setName(cursor.getString(nameColumnIndex));
                }
                if (majorColumnIndex >= 0) {
                    student.setMajor(cursor.getString(majorColumnIndex));
                }

                // 只有当所有必要的字段都获取成功时才添加到列表
                if (student.getId() != null && student.getName() != null && student.getMajor() != null) {
                    studentList.add(student);
                }

            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();

        return studentList;
    }
    /**
     * 获取所有学生信息
     * @return 所有的学生列表
     */
    @SuppressLint("Range")
    public List<Student> getAllStudents() {
        List<Student> studentList = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME_STUDENTS, null, null, null, null, null, null);

        if (cursor.moveToFirst()) {
            do {
                Student student = new Student();
                student.setId(cursor.getString(cursor.getColumnIndex(COLUMN_ID)));
                student.setName(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
                student.setMajor(cursor.getString(cursor.getColumnIndex(COLUMN_MAJOR)));
                studentList.add(student);
            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();

        return studentList;
    }

    /**
     * 根据学生ID从数据库中删除学生信息
     * @param studentId 要删除的学生的ID
     */
    public void deleteStudent(String studentId) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NAME_STUDENTS, COLUMN_ID + "=?", new String[]{studentId});
        db.close(); // 关闭数据库连接
    }

}

SearchStudentFragment类

package com.example.myfinalwork;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;


public class SearchStudentFragment extends Fragment {

    private EditText editTextSearchQuery;
    private RadioButton radioButtonByName, radioButtonById,radioButtonByMajor;
    private RecyclerView recyclerViewSearchResults;
    private SearchListAdapter searchResultsAdapter;
    private List<Student> searchedStudents;
    private StudentDBHelper dbHelper;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_search_student, container, false);

        // 初始化控件引用
        editTextSearchQuery = rootView.findViewById(R.id.edit_text_search_query);
        radioButtonByName = rootView.findViewById(R.id.radio_button_name);
        radioButtonById = rootView.findViewById(R.id.radio_button_id);
        radioButtonByMajor = rootView.findViewById(R.id.radio_button_major);
        recyclerViewSearchResults = rootView.findViewById(R.id.recycler_view_search_results);
        recyclerViewSearchResults.setLayoutManager(new LinearLayoutManager(requireContext()));

        // 初始化数据库帮助类
        dbHelper = new StudentDBHelper(getActivity().getApplicationContext());

        // 初始化搜索结果列表的适配器
        searchedStudents = new ArrayList<>();
        searchResultsAdapter = new SearchListAdapter(requireContext(), searchedStudents);
        recyclerViewSearchResults.setAdapter(searchResultsAdapter);


        // 添加搜索按钮点击事件监听器
        Button buttonSearch = rootView.findViewById(R.id.button_search);
        buttonSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String query = editTextSearchQuery.getText().toString().trim();
                String searchBy;

                if (radioButtonByName.isChecked()) {
                    searchBy = "name";
                } else if (radioButtonById.isChecked()) {
                    searchBy = "id";
                } else if (radioButtonByMajor.isChecked()) { // 新增部分
                    searchBy = "major";
                } else {
                    searchBy = "name"; // 默认值,如果都没有选中则按照姓名搜索
                }

                if (!query.isEmpty()) {
                    searchedStudents.clear();
                    List<Student> students = dbHelper.searchStudents(query, searchBy);
                    searchedStudents.addAll(students);
                    searchResultsAdapter.notifyDataSetChanged();

                    if (searchedStudents.isEmpty()) {
                        Toast.makeText(getContext(), "未找到匹配的学生", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getContext(), "请输入搜索关键词", Toast.LENGTH_SHORT).show();
                }
            }
        });

        return rootView;

    }


}

 SearchListAdapter类

package com.example.myfinalwork;

        import android.content.Context;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.CheckBox;
        import android.widget.TextView;

        import androidx.annotation.NonNull;
        import androidx.recyclerview.widget.RecyclerView;

        import java.util.List;

public class SearchListAdapter extends RecyclerView.Adapter<SearchListAdapter.StudentViewHolder> {

    private Context context;
    private List<Student> studentList;


    public SearchListAdapter(Context context, List<Student> studentList) {
        this.context = context;
        this.studentList = studentList;
    }





    @NonNull
    @Override
    public StudentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.item_student2, parent, false);
        return new StudentViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull StudentViewHolder holder, int position) {
        final Student currentStudent = studentList.get(position);

        holder.studentName.setText(currentStudent.getName());
        holder.studentId.setText(currentStudent.getId());
        holder.studentMajor.setText(currentStudent.getMajor());


    }

    @Override
    public int getItemCount() {
        return studentList.size();
    }

    // ViewHolder 类用于缓存视图组件
    public static class StudentViewHolder extends RecyclerView.ViewHolder {
        TextView studentName, studentId, studentMajor;
        CheckBox checkBoxSelect;

        public StudentViewHolder(@NonNull View itemView) {
            super(itemView);

            studentName = itemView.findViewById(R.id.text_view_student_name);
            studentId = itemView.findViewById(R.id.text_view_student_id);
            studentMajor = itemView.findViewById(R.id.text_view_student_major);
            checkBoxSelect = itemView.findViewById(R.id.check_box_select);
        }
    }
}

 StudentListFragment类

package com.example.myfinalwork;


import android.app.AlertDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;


import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import java.util.ArrayList;
import java.util.List;


public class StudentListFragment extends Fragment implements StudentListAdapter.OnItemSelectedListener {


    private RecyclerView recyclerView;
    private StudentListAdapter adapter;
    private List<Student> studentList;
    private Button deleteButton;
    private List<Student> selectedStudents = new ArrayList<>();
    private StudentDBHelper dbHelper;
    private AlertDialog deleteConfirmationDialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 加载fragment布局
        View rootView = inflater.inflate(R.layout.fragment_student_list, container, false);

        // 初始化数据库助手
        dbHelper = new StudentDBHelper(requireContext());

        // 初始化RecyclerView和Adapter
        recyclerView = rootView.findViewById(R.id.recycler_view_students);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));

        // 这里可以填充或从数据库加载学生数据
        // 初始化数据列表
        studentList = new ArrayList<>();
        studentList = dbHelper.getAllStudents();

        // 创建并设置Adapter
        adapter = new StudentListAdapter(requireContext(), studentList);
        adapter.setOnItemSelectedListener(this); // 设置选择监听器
        recyclerView.setAdapter(adapter);

        // 获取并设置删除按钮点击事件
        deleteButton = rootView.findViewById(R.id.button_delete);
        deleteButton.setOnClickListener(v -> showDeleteConfirmationDialog());

        // 获取并设置刷新按钮点击事件
        Button refreshButton = rootView.findViewById(R.id.button_refresh);
        refreshButton.setOnClickListener(v -> {

            refreshStudentList();

            Toast.makeText(requireContext(), "学生列表已刷新", Toast.LENGTH_SHORT).show();
        });


        return rootView;
    }

    // 显示删除确认对话框
    private void showDeleteConfirmationDialog() {
        if (!selectedStudents.isEmpty()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            View dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_delete_confirm, null);

            Button btnCancel = dialogView.findViewById(R.id.button_cancel);
            Button btnDelete = dialogView.findViewById(R.id.button_delete);

            btnCancel.setOnClickListener(v -> deleteConfirmationDialog.dismiss());
            btnDelete.setOnClickListener(v -> {
                for (Student student : selectedStudents) {
                    dbHelper.deleteStudent(student.getId()); // 从数据库中删除学生
                    studentList.remove(student); // 从列表中移除学生
                }
                selectedStudents.clear(); // 清空已删除的学生列表
                adapter.notifyDataSetChanged(); // 刷新RecyclerView

                deleteConfirmationDialog.dismiss();
                Toast.makeText(requireContext(), "删除成功", Toast.LENGTH_SHORT).show();
            });

            deleteConfirmationDialog = builder.setView(dialogView)
                    .setTitle("删除确认")
                    .create();
            deleteConfirmationDialog.show();
        } else {
            Toast.makeText(requireContext(), "请先选择要删除的学生", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onItemSelected(Student student, boolean selected) {
        if (selected) {
            selectedStudents.add(student);
        } else {
            selectedStudents.remove(student);
        }
    }

    public void refreshStudentList() {
        // 从数据库重新获取学生数据
        studentList.clear(); // 清空现有数据
        studentList.addAll(dbHelper.getAllStudents()); // 将新数据添加到studentList
        adapter.notifyDataSetChanged(); // 刷新RecyclerView的数据
    }

}

StudentListAdapter类

package com.example.myfinalwork;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class StudentListAdapter extends RecyclerView.Adapter<StudentListAdapter.StudentViewHolder> {

    private Context context;
    private List<Student> studentList;
    private OnItemSelectedListener listener;

    public StudentListAdapter(Context context, List<Student> studentList) {
        this.context = context;
        this.studentList = studentList;
    }

    // 添加一个接口,用于监听选择事件
    public interface OnItemSelectedListener {
        void onItemSelected(Student student, boolean selected);
    }

    public void setOnItemSelectedListener(OnItemSelectedListener listener) {
        this.listener = listener;
    }

    @NonNull
    @Override
    public StudentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.item_student1, parent, false);
        return new StudentViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull StudentViewHolder holder, int position) {
        final Student currentStudent = studentList.get(position);

        holder.studentName.setText(currentStudent.getName());
        holder.studentId.setText(currentStudent.getId());
        holder.studentMajor.setText(currentStudent.getMajor());

        holder.checkBoxSelect.setChecked(currentStudent.isSelected());
        holder.checkBoxSelect.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (listener != null) {
                currentStudent.setSelected(isChecked);
                listener.onItemSelected(currentStudent, isChecked);
            }
        });
    }

    @Override
    public int getItemCount() {
        return studentList.size();
    }

    // ViewHolder 类用于缓存视图组件
    public static class StudentViewHolder extends RecyclerView.ViewHolder {
        TextView studentName, studentId, studentMajor;
        CheckBox checkBoxSelect;

        public StudentViewHolder(@NonNull View itemView) {
            super(itemView);

            studentName = itemView.findViewById(R.id.text_view_student_name);
            studentId = itemView.findViewById(R.id.text_view_student_id);
            studentMajor = itemView.findViewById(R.id.text_view_student_major);
            checkBoxSelect = itemView.findViewById(R.id.check_box_select);
        }
    }
}

AddStudentFragment类

package com.example.myfinalwork;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import java.util.List;

public class AddStudentFragment extends Fragment {

    private EditText editTextName, editTextId, editTextMajor;
    private Button buttonSubmit;
    private StudentDBHelper dbHelper;
    private StudentListRefreshListener refreshListener; // 移除MainActivity前缀,因为它是一个接口引用

    public void setStudentListRefreshListener(StudentListRefreshListener listener) {
        this.refreshListener = listener;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_add_student, container, false);

        // 初始化控件引用
        editTextName = rootView.findViewById(R.id.edit_text_name);
        editTextId = rootView.findViewById(R.id.edit_text_student_id);
        editTextMajor = rootView.findViewById(R.id.edit_text_major);
        buttonSubmit = rootView.findViewById(R.id.button_submit);

        // 初始化数据库帮助类
        dbHelper = new StudentDBHelper(getActivity().getApplicationContext());

        // 获取宿主Activity的引用并设置监听器(已在setupViewPager()中完成)

        // 添加提交按钮点击事件监听器
        buttonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = editTextName.getText().toString().trim();
                String id = editTextId.getText().toString().trim();
                String major = editTextMajor.getText().toString().trim();

                if (!name.isEmpty() && !id.isEmpty() && !major.isEmpty()) {
                    Student newStudent = new Student(id, name, major);
                    dbHelper.insertStudent(newStudent);

                    editTextName.setText("");
                    editTextId.setText("");
                    editTextMajor.setText("");

                    Toast.makeText(getContext(), "学生信息已添加", Toast.LENGTH_SHORT).show();

                    // 添加完学生后,通知宿主Activity刷新学生列表
                    if (refreshListener != null) {
                        refreshListener.onStudentListRefresh();
                    }

                } else {
                    Toast.makeText(getContext(), "请确保所有字段都已填写", Toast.LENGTH_SHORT).show();
                }
            }
        });

        return rootView;
    }
}

 StudentListRefreshListener接口

package com.example.myfinalwork;

public interface StudentListRefreshListener {
    void onStudentListRefresh();
}

XML布局文件 

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:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottom_navigation_menu" />

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/view_pager"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/bottom_navigation_view"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

dialog_delete_confirm.xml 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="24dp"
    android:background="@color/white">

    <!-- 提示信息 -->
    <TextView
        android:id="@+id/text_view_dialog_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:textStyle="bold"
        android:textColor="@color/black"
        android:text="确定要删除吗?" />

    <!-- 水平分割线 -->
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/black" />

    <!-- 确认和取消按钮 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="end"
        android:paddingTop="16dp">

        <Button
            android:id="@+id/button_cancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="取消"
            android:textStyle="bold"
            android:textColor="@color/black"
            android:background="?attr/selectableItemBackgroundBorderless"
            android:minWidth="96dp" />

        <Button
            android:id="@+id/button_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="确定"
            android:textStyle="bold"
            android:textColor="@color/black"
            android:background="?attr/selectableItemBackgroundBorderless"
            android:minWidth="96dp"
            android:layout_marginStart="16dp" />

    </LinearLayout>

</LinearLayout>

 fragment_add_student.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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <!-- 姓名输入框 -->
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/th"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toTopOf="@id/edit_text_name" />

    <!-- 姓名输入框 -->
    <EditText
        android:id="@+id/edit_text_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="姓名"
        android:inputType="textPersonName"
        app:layout_constraintTop_toBottomOf="@id/imageView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginTop="32dp" />

    <!-- 学号输入框 -->
    <EditText
        android:id="@+id/edit_text_student_id"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="学号"
        android:inputType="number"
        app:layout_constraintTop_toBottomOf="@id/edit_text_name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginTop="16dp" />

    <!-- 专业输入框 -->
    <EditText
        android:id="@+id/edit_text_major"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="专业"
        android:inputType="text"
        app:layout_constraintTop_toBottomOf="@id/edit_text_student_id"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginTop="16dp" />

    <!-- 提交按钮 -->
    <Button
        android:id="@+id/button_submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="68dp"
        android:text="确定"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/edit_text_major" />

</androidx.constraintlayout.widget.ConstraintLayout>

 fragment_search_student.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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <!-- 搜索栏 -->
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/text_input_layout_search"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/edit_text_search_query"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="搜索姓名或学号"
            android:inputType="text|textCapWords|textMultiLine|textAutoComplete|textAutoCorrect"/>

    </com.google.android.material.textfield.TextInputLayout>

    <!-- 查询条件选择 -->
    <RadioGroup
        android:id="@+id/radio_group_search_by"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:checkedButton="@+id/radio_button_name"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/text_input_layout_search">

        <RadioButton
            android:id="@+id/radio_button_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按姓名搜索" />

        <RadioButton
            android:id="@+id/radio_button_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按学号搜索" />

        <RadioButton
            android:id="@+id/radio_button_major"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按专业搜索" />

    </RadioGroup>

    <!-- 搜索结果列表 -->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view_search_results"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scrollbars="vertical"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toTopOf="@+id/button_search_container"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/radio_group_search_by" />

    <!-- 搜索按钮容器,用于将两个按钮保持在同一行且居中 -->
    <LinearLayout
        android:id="@+id/button_search_container"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <!-- 搜索按钮 -->
        <Button
            android:id="@+id/button_search"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="搜索"
            android:layout_marginEnd="8dp" />



    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

 fragment_student_list.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:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/toolbar"
        android:layout_width="0dp"
        android:layout_height="?attr/actionBarSize"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:title="学生信息管理"
        app:titleCentered="true"/>

    <!-- 分割线 -->
    <View
        android:id="@+id/view_separator"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@android:color/black"
        app:layout_constraintBottom_toTopOf="@+id/recycler_view_students"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar" />

    <!-- RecyclerView -->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view_students"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toTopOf="@+id/button_container"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view_separator" />

    <!-- 按钮容器,用于包含“删除”和“刷新”按钮 -->
    <LinearLayout
        android:id="@+id/button_container"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <!-- 删除按钮 -->
        <Button
            android:id="@+id/button_delete"
            android:layout_width="0dp"
            android:layout_height="46dp"
            android:layout_weight="1"
            android:text="删除"
            android:textAllCaps="false"
            android:textColor="@android:color/white"
            android:layout_marginEnd="8dp" />

        <!-- 刷新按钮 -->
        <Button
            android:id="@+id/button_refresh"
            android:layout_width="0dp"
            android:layout_height="46dp"
            android:layout_weight="1"
            android:text="刷新"
            android:textAllCaps="false"
            android:textColor="@android:color/white" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

item_student1.xml

<!-- item_student.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="16dp">

    <!-- 学生姓名 -->
    <TextView
        android:id="@+id/text_view_student_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="16sp" />

    <!-- 学生学号 -->
    <TextView
        android:id="@+id/text_view_student_id"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="14sp"
        android:layout_marginStart="16dp" />

    <!-- 学生专业 -->
    <TextView
        android:id="@+id/text_view_student_major"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="14sp"
        android:layout_marginStart="16dp" />

    <!-- 选中框 -->
    <CheckBox
        android:id="@+id/check_box_select"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:checked="false"
        android:layout_marginStart="16dp" />

</LinearLayout>

 item_student2.xml

<!-- item_student.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="16dp">

    <!-- 学生姓名 -->
    <TextView
        android:id="@+id/text_view_student_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="16sp" />

    <!-- 学生学号 -->
    <TextView
        android:id="@+id/text_view_student_id"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="14sp"
        android:layout_marginStart="16dp" />

    <!-- 学生专业 -->
    <TextView
        android:id="@+id/text_view_student_major"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="14sp"
        android:layout_marginStart="16dp" />

    <!-- 选中框 -->

</LinearLayout>

 bottom_navigation_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@id/action_student_list"
        android:icon="@android:drawable/ic_dialog_dialer"
        android:title="学生列表" />
    <item
        android:id="@id/action_add_student"
        android:icon="@android:drawable/ic_input_add"
        android:title="添加" />
    <item
        android:id="@id/action_search_student"
        android:icon="@android:drawable/ic_menu_search"
        android:title="搜索" />
</menu>
Top