APP开发

APP开发menuxmlns android http schemas android com apk res android itemandroid id id nav my notes android title 我的 itemandroid id id nav settings android title 设置 app 开发

1. 创建菜单资源文件

res/menu 目录下创建一个新的菜单资源文件 main_menu.xml

main_menu.xml

<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/nav_my_notes" android:title="我的"/> <item android:id="@+id/nav_settings" android:title="设置"/> </menu> 

2. 修改 MainActivity 布局文件

activity_main.xml 中,设置 Toolbar 以支持菜单的显示。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/> <FrameLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/toolbar"/> </RelativeLayout> 

3. 修改 MainActivity 代码

MainActivity.java

package com.example.notesapp; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; public class MainActivity extends AppCompatActivity { 
    private String username; @Override protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 设置Toolbar androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); username = getIntent().getStringExtra("username"); if (username == null) { 
    Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show(); startActivity(new Intent(this, LoginActivity.class)); finish(); return; } // 默认显示"我的"页面 if (savedInstanceState == null) { 
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MyNotesFragment()).commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { 
    Fragment selectedFragment = null; switch (item.getItemId()) { 
    case R.id.nav_my_notes: selectedFragment = new MyNotesFragment(); break; case R.id.nav_settings: selectedFragment = new SettingsFragment(); break; default: return super.onOptionsItemSelected(item); } getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit(); return true; } } 

4. 添加依赖和主题配置

确保在 build.gradle 文件中添加了 appcompat 库依赖,并在 styles.xml 中配置主题。

build.gradle

dependencies { implementation 'androidx.appcompat:appcompat:1.3.0' implementation 'com.google.android.material:material:1.3.0' // 其他依赖项... } 

styles.xml

<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> </resources> 

5. 测试应用

MainActivity 中运行应用程序,右上角的菜单按钮,应该会显示“我的”和“设置”选项。这些选项将会加载相应的Fragment。

这样可以实现你提供的截图中所展示的界面。下面是 MyNotesFragmentSettingsFragment 的代码示例,供参考。

MyNotesFragment 示例

MyNotesFragment.java

package com.example.notesapp; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import java.util.ArrayList; public class MyNotesFragment extends Fragment { 
    private SQLiteDatabase db; private ListView listView; private ArrayAdapter<String> adapter; private ArrayList<String> notesList; private String username; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.fragment_my_notes, container, false); // 初始化数据库 NotesDBHelper dbHelper = new NotesDBHelper(getActivity()); db = dbHelper.getWritableDatabase(); listView = view.findViewById(R.id.notes_list); Button addButton = view.findViewById(R.id.add_note_button); // 获取用户名 MainActivity activity = (MainActivity) getActivity(); if (activity != null) { 
    username = activity.getIntent().getStringExtra("username"); } notesList = new ArrayList<>(); adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, notesList); listView.setAdapter(adapter); loadNotes(); addButton.setOnClickListener(new View.OnClickListener() { 
    @Override public void onClick(View v) { 
    // 跳转到新增笔记页面 Intent intent = new Intent(getActivity(), EditNoteActivity.class); intent.putExtra("username", username); startActivity(intent); } }); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
    @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
    // 跳转到编辑笔记页面 String note = notesList.get(position); Intent intent = new Intent(getActivity(), EditNoteActivity.class); intent.putExtra("note", note); intent.putExtra("username", username); startActivity(intent); } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { 
    @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { 
    new AlertDialog.Builder(getActivity()) .setTitle("删除笔记") .setMessage("确定要删除这条笔记吗?") .setPositiveButton("删除", (dialog, which) -> { 
    String note = notesList.get(position); deleteNote(note); notesList.remove(position); adapter.notifyDataSetChanged(); }) .setNegativeButton("取消", null) .show(); return true; } }); return view; } private void loadNotes() { 
    notesList.clear(); Cursor cursor = db.query("notes", null, "username=?", new String[]{ 
   username}, null, null, "timestamp DESC"); if (cursor != null) { 
    while (cursor.moveToNext()) { 
    String title = cursor.getString(cursor.getColumnIndex("title")); String content = cursor.getString(cursor.getColumnIndex("content")); notesList.add(title + "\n" + content); } cursor.close(); } adapter.notifyDataSetChanged(); } private void deleteNote(String note) { 
    db.delete("notes", "username=? AND content=?", new String[]{ 
   username, note}); } } 

fragment_my_notes.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:orientation="vertical" android:padding="16dp"> <Button android:id="@+id/add_note_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="新增笔记" /> <ListView android:id="@+id/notes_list" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" /> </LinearLayout> 

SettingsFragment 示例

SettingsFragment.java

package com.example.notesapp; import android.content.ContentValues; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; 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.annotation.Nullable; import androidx.fragment.app.Fragment; public class SettingsFragment extends Fragment { 
    private EditText nicknameEditText, passwordEditText, confirmPasswordEditText; private Button saveButton, logoutButton; private SQLiteDatabase db; private String username; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.fragment_settings, container, false); nicknameEditText = view.findViewById(R.id.nickname); passwordEditText = view.findViewById(R.id.password); confirmPasswordEditText = view.findViewById(R.id.confirmPassword); saveButton = view.findViewById(R.id.save); logoutButton = view.findViewById(R.id.logout); NotesDBHelper dbHelper = new NotesDBHelper(getActivity()); db = dbHelper.getWritableDatabase(); MainActivity activity = (MainActivity) getActivity(); if (activity != null) { 
    username = activity.getIntent().getStringExtra("username"); } saveButton.setOnClickListener(new View.OnClickListener() { 
    @Override public void onClick(View v) { 
    String nickname = nicknameEditText.getText().toString(); String password = passwordEditText.getText().toString(); String confirmPassword = confirmPasswordEditText.getText().toString(); if (!TextUtils.isEmpty(password) && !password.equals(confirmPassword)) { 
    Toast.makeText(getActivity(), "密码和确认密码不一致", Toast.LENGTH_SHORT).show(); return; } ContentValues values = new ContentValues(); if (!TextUtils.isEmpty(nickname)) { 
    values.put("nickname", nickname); } if (!TextUtils.isEmpty(password)) { 
    values.put("password", password); } if (values.size() > 0) { 
    db.update("users", values, "username=?", new String[]{ 
   username}); Toast.makeText(getActivity(), "信息已更新", Toast.LENGTH_SHORT).show(); } else { 
    Toast.makeText(getActivity(), "没有要更新的信息", Toast.LENGTH_SHORT).show(); } } }); logoutButton.setOnClickListener(new View.OnClickListener() { 
    @Override public void onClick(View v) { 
    Intent intent = new Intent(getActivity(), LoginActivity.class); startActivity(intent); if (getActivity() != null) { 
    getActivity().finish(); } } }); return view; } } 

fragment_settings.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:orientation="vertical" android:padding="16dp"> <EditText android:id="@+id/nickname" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="昵称" /> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="密码" android:inputType="textPassword" /> <EditText android:id="@+id/confirmPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="确认密码" android:inputType="textPassword" /> <Button android:id="@+id/save" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="保存" /> <Button android:id="@+id/logout" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="退出登录" /> </LinearLayout> 

完整代码总结

  1. main_menu.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/nav_my_notes" android:title="我的"/> <item android:id="@+id/nav_settings" android:title="设置"/> </menu> 

2.activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/> <FrameLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/toolbar"/> </RelativeLayout> 

MainActivity.java

package com.example.notesapp; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; public class MainActivity extends AppCompatActivity { 
    private String username; @Override protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 设置Toolbar androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); username = getIntent().getStringExtra("username"); if (username == null) { 
    Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show(); startActivity(new Intent(this, LoginActivity.class)); finish(); return; } // 默认显示"我的"页面 if (savedInstanceState == null) { 
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MyNotesFragment()).commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { 
    Fragment selectedFragment = null; switch (item.getItemId()) { 
    case R.id.nav_my_notes: selectedFragment = new MyNotesFragment(); break; case R.id.nav_settings: selectedFragment = new SettingsFragment(); break; default: return super.onOptionsItemSelected(item); } getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit(); return true; } } 

MyNotesFragment.java

package com.example.notesapp; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import java.util.ArrayList; public class MyNotesFragment extends Fragment { 
    private SQLiteDatabase db; private ListView listView; private ArrayAdapter<String> adapter; private ArrayList<String> notesList; private String username; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.fragment_my_notes, container, false); // 初始化数据库 NotesDBHelper dbHelper = new NotesDBHelper(getActivity()); db = dbHelper.getWritableDatabase(); listView = view.findViewById(R.id.notes_list); Button addButton = view.findViewById(R.id.add_note_button); // 获取用户名 MainActivity activity = (MainActivity) getActivity(); if (activity != null) { 
    username = activity.getIntent().getStringExtra("username"); } notesList = new ArrayList<>(); adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, notesList); listView.setAdapter(adapter); loadNotes(); addButton.setOnClickListener(new View.OnClickListener() { 
    @Override public void onClick(View v) { 
    // 跳转到新增笔记页面 Intent intent = new Intent(getActivity(), EditNoteActivity.class); intent.putExtra("username", username); startActivity(intent); } }); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
    @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
    // 跳转到编辑笔记页面 String note = notesList.get(position); Intent intent = new Intent(getActivity(), EditNoteActivity.class); intent.putExtra("note", note); intent.putExtra("username", username); startActivity(intent); } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { 
    @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { 
    new AlertDialog.Builder(getActivity()) .setTitle("删除笔记") .setMessage("确定要删除这条笔记吗?") .setPositiveButton("删除", (dialog, which) -> { 
    String note = notesList.get(position); deleteNote(note); notesList.remove(position); adapter.notifyDataSetChanged(); }) .setNegativeButton("取消", null) .show(); return true; } }); return view; } private void loadNotes() { 
    notesList.clear(); Cursor cursor = db.query("notes", null, "username=?", new String[]{ 
   username}, null, null, "timestamp DESC"); if (cursor != null) { 
    while (cursor.moveToNext()) { 
    String title = cursor.getString(cursor.getColumnIndex("title")); String content = cursor.getString(cursor.getColumnIndex("content")); notesList.add(title + "\n" + content); } cursor.close(); } adapter.notifyDataSetChanged(); } private void deleteNote(String note) { 
    db.delete("notes", "username=? AND content=?", new String[]{ 
   username, note}); } } 

fragment_my_notes.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:orientation="vertical" android:padding="16dp"> <Button android:id="@+id/add_note_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="新增笔记" /> <ListView android:id="@+id/notes_list" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" /> </LinearLayout> 

SettingsFragment.java

package com.example.notesapp; import android.content.ContentValues; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; 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.annotation.Nullable; import androidx.fragment.app.Fragment; public class SettingsFragment extends Fragment { 
    private EditText nicknameEditText, passwordEditText, confirmPasswordEditText; private Button saveButton, logoutButton; private SQLiteDatabase db; private String username; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.fragment_settings, container, false); nicknameEditText = view.findViewById(R.id.nickname); passwordEditText = view.findViewById(R.id.password); confirmPasswordEditText = view.findViewById(R.id.confirmPassword); saveButton = view.findViewById(R.id.save); logoutButton = view.findViewById(R.id.logout); NotesDBHelper dbHelper = new NotesDBHelper(getActivity()); db = dbHelper.getWritableDatabase(); MainActivity activity = (MainActivity) getActivity(); if (activity != null) { 
    username = activity.getIntent().getStringExtra("username"); } saveButton.setOnClickListener(new View.OnClickListener() { 
    @Override public void onClick(View v) { 
    String nickname = nicknameEditText.getText().toString(); String password = passwordEditText.getText().toString(); String confirmPassword = confirmPasswordEditText.getText().toString(); if (!TextUtils.isEmpty(password) && !password.equals(confirmPassword)) { 
    Toast.makeText(getActivity(), "密码和确认密码不一致", Toast.LENGTH_SHORT).show(); return; } ContentValues values = new ContentValues(); if (!TextUtils.isEmpty(nickname)) { 
    values.put("nickname", nickname); } if (!TextUtils.isEmpty(password)) { 
    values.put("password", password); } if (values.size() > 0) { 
    db.update("users", values, "username=?", new String[]{ 
   username}); Toast.makeText(getActivity(), "信息已更新", Toast.LENGTH_SHORT).show(); } else { 
    Toast.makeText(getActivity(), "没有要更新的信息", Toast.LENGTH_SHORT).show(); } } }); logoutButton.setOnClickListener(new View.OnClickListener() { 
    @Override public void onClick(View v) { 
    Intent intent = new Intent(getActivity(), LoginActivity.class); startActivity(intent); if (getActivity() != null) { 
    getActivity().finish(); } } }); return view; } } 

fragment_settings.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:orientation="vertical" android:padding="16dp"> <EditText android:id="@+id/nickname" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="昵称" /> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="密码" android:inputType="textPassword" /> <EditText android:id="@+id/confirmPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="确认密码" android:inputType="textPassword" /> <Button android:id="@+id/save" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="保存" /> <Button android:id="@+id/logout" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="退出登录" /> </LinearLayout> 
今天的文章 APP开发分享到此就结束了,感谢您的阅读。
编程小号
上一篇 2024-12-30 20:46
下一篇 2024-12-30 20:40

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ji-chu/91945.html