?歡迎光臨:
古之立大事者,不惟有超世之才,亦必有堅忍不拔之志?!K軾
---------------??------------??--------------
??學編程的bird的博客,邀您一起學習??
----------------??------------??-------------??很高興你打開了這篇博客。
★如有疑問不解或者說有想問的地方,都可以在下方評論留言,博主看到會盡快回復的。
★當然,期待你的點贊+關注哦!★本人微信:wxid_v28nw5cckzz622,若需要幫助,請備注來源+意圖
————————————————
版權(quán)聲明:本文為CSDN博主「學編程的bird」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接及本聲明。
原文鏈接:Android Studio 大作業(yè)--學生信息管理系統(tǒng)-CSDN博客https://blog.csdn.net/m0_64069699/article/details/135324803
內(nèi)容大概:
簡易學生信息管理系統(tǒng)項目需求,大致需要以下Java文件和XML布局文件: Java文件: Student 類(實體類):用于存儲學生信息。 StudentDBHelper 類(數(shù)據(jù)庫操作類):繼承自SQLiteOpenHelper,負責創(chuàng)建表、插入、刪除、更新和查詢學生數(shù)據(jù)。 StudentListAdapter 類(RecyclerView Adapter):適配器類,用于在“學生列表”模塊展示學生數(shù)據(jù)。 StudentListFragment 類(Fragment):實現(xiàn)學生列表界面功能,包含RecyclerView及其Adapter的初始化等。 AddStudentFragment 類(Fragment):實現(xiàn)添加學生界面功能,包含EditText輸入框、Button提交按鈕、ImageView頭像選擇等。 SearchStudentFragment 類(Fragment):實現(xiàn)查詢學生界面功能,包含EditText輸入框、CheckBox或RadioButton查詢條件選擇、查詢結(jié)果展示列表的初始化等。 SearchStudentListAdapter 類(RecyclerView Adapter):適配器類,用于在“搜索”模塊展示學生數(shù)據(jù)。 MainActivity:用于初始化底部導航欄與ViewPager2,并管理各個Fragment。 XML布局文件: activity_main.xml:主Activity布局文件,包含ViewPager2和TabLayout等控件。 fragment_student_list.xml:學生列表Fragment的布局文件,包含RecyclerView等控件。 fragment_add_student.xml:添加學生Fragment的布局文件,包含姓名、學號、專業(yè)等EditText輸入框以及上傳或選擇圖片的ImageView和提交按鈕等控件。 item_student1.xml:RecyclerView中單個學生項的布局文件,包含顯示學生信息的各種TextView、ImageView等控件。 fragment_search_student.xml:查詢學生Fragment的布局文件,包含查詢輸入框、查詢條件選擇控件以及查詢結(jié)果展示的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 跳轉(zhuǎn)和傳值、ViewPager2+Fragment 底部導航 PopupWindow & AlertDialog、數(shù)據(jù)庫 RadioButton、CheckBox、返回值、RecyclerView
整體架構(gòu):
?示例展示:
學生列表
?添加
文章來源:http://www.zghlxwxcb.cn/news/detail-785237.html
?搜索
文章來源地址http://www.zghlxwxcb.cn/news/detail-785237.html
源代碼:?
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設置一個接口回調(diào)以通知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 { // 數(shù)據(jù)庫名稱 private static final String DATABASE_NAME = "StudentManager.db"; // 數(shù)據(jù)庫版本號,每次更新數(shù)據(jù)庫結(jié)構(gòu)時需要增加 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"; // 創(chuàng)建學生信息表的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) { // 在數(shù)據(jù)庫版本升級時,可以在此處添加數(shù)據(jù)遷移邏輯或者刪除舊表重建新表 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_STUDENTS); onCreate(db); } /** * 一個簡單的方法用于將學生信息插入數(shù)據(jù)庫,具體實現(xiàn)由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(); // 關閉數(shù)據(jù)庫連接 } /** * 根據(jù)查詢條件搜索學生 * @param query 搜索關鍵詞 * @param searchBy 搜索依據(jù)字段("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; } /** * 根據(jù)學生ID從數(shù)據(jù)庫中刪除學生信息 * @param studentId 要刪除的學生的ID */ public void deleteStudent(String studentId) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_NAME_STUDENTS, COLUMN_ID + "=?", new String[]{studentId}); db.close(); // 關閉數(shù)據(jù)庫連接 } }
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())); // 初始化數(shù)據(jù)庫幫助類 dbHelper = new StudentDBHelper(getActivity().getApplicationContext()); // 初始化搜索結(jié)果列表的適配器 searchedStudents = new ArrayList<>(); searchResultsAdapter = new SearchListAdapter(requireContext(), searchedStudents); recyclerViewSearchResults.setAdapter(searchResultsAdapter); // 添加搜索按鈕點擊事件監(jiān)聽器 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); // 初始化數(shù)據(jù)庫助手 dbHelper = new StudentDBHelper(requireContext()); // 初始化RecyclerView和Adapter recyclerView = rootView.findViewById(R.id.recycler_view_students); recyclerView.setLayoutManager(new LinearLayoutManager(requireContext())); // 這里可以填充或從數(shù)據(jù)庫加載學生數(shù)據(jù) // 初始化數(shù)據(jù)列表 studentList = new ArrayList<>(); studentList = dbHelper.getAllStudents(); // 創(chuàng)建并設置Adapter adapter = new StudentListAdapter(requireContext(), studentList); adapter.setOnItemSelectedListener(this); // 設置選擇監(jiān)聽器 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()); // 從數(shù)據(jù)庫中刪除學生 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() { // 從數(shù)據(jù)庫重新獲取學生數(shù)據(jù) studentList.clear(); // 清空現(xiàn)有數(shù)據(jù) studentList.addAll(dbHelper.getAllStudents()); // 將新數(shù)據(jù)添加到studentList adapter.notifyDataSetChanged(); // 刷新RecyclerView的數(shù)據(jù) } }
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; } // 添加一個接口,用于監(jiān)聽選擇事件 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); // 初始化數(shù)據(jù)庫幫助類 dbHelper = new StudentDBHelper(getActivity().getApplicationContext()); // 獲取宿主Activity的引用并設置監(jiān)聽器(已在setupViewPager()中完成) // 添加提交按鈕點擊事件監(jiān)聽器 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" /> <!-- 專業(yè)輸入框 --> <EditText android:id="@+id/edit_text_major" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="專業(yè)" 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="搜索姓名或?qū)W號" 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="按專業(yè)搜索" /> </RadioGroup> <!-- 搜索結(jié)果列表 --> <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" /> <!-- 學生專業(yè) --> <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" /> <!-- 學生專業(yè) --> <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>
到了這里,關于Android Studio 大作業(yè)--學生信息管理系統(tǒng)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!