实践案例:使用Jetpack Navigation创建一个新闻应用

server/2024/9/23 3:23:19/

在这里插入图片描述

在这个实践案例中,我们将使用Jetpack Navigation创建一个简单的新闻应用。这个应用将包含以下功能:

  1. 新闻列表页面:显示一组新闻文章。
  2. 新闻详情页面:显示选定新闻文章的详细信息。
  3. 用户资料页面:显示用户的资料信息。

我们将通过导航图、传递数据、处理返回操作和集成底部导航来展示Jetpack Navigation的强大功能。

第一步:项目设置

添加依赖项

build.gradle文件中添加必要的依赖项:

dependencies {def nav_version = "2.4.0"implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"implementation "androidx.navigation:navigation-ui-ktx:$nav_version"implementation "com.google.android.material:material:1.4.0"
}

创建导航图

res/navigation目录中创建一个新的导航图文件nav_graph.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation 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"app:startDestination="@id/newsListFragment"><fragmentandroid:id="@+id/newsListFragment"android:name="com.example.newsapp.NewsListFragment"android:label="News List"tools:layout="@layout/fragment_news_list" ><actionandroid:id="@+id/action_newsListFragment_to_newsDetailFragment"app:destination="@id/newsDetailFragment" /><actionandroid:id="@+id/action_newsListFragment_to_userProfileFragment"app:destination="@id/userProfileFragment" /></fragment><fragmentandroid:id="@+id/newsDetailFragment"android:name="com.example.newsapp.NewsDetailFragment"android:label="News Detail"tools:layout="@layout/fragment_news_detail" ><argumentandroid:name="articleId"app:argType="integer" /></fragment><fragmentandroid:id="@+id/userProfileFragment"android:name="com.example.newsapp.UserProfileFragment"android:label="User Profile"tools:layout="@layout/fragment_user_profile" /></navigation>

主Activity布局

创建主Activity布局文件activity_main.xml,包含一个NavHostFragmentBottomNavigationView

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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"><androidx.constraintlayout.widget.ConstraintLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"><fragmentandroid:id="@+id/nav_host_fragment"android:name="androidx.navigation.fragment.NavHostFragment"android:layout_width="0dp"android:layout_height="0dp"app:defaultNavHost="true"app:navGraph="@navigation/nav_graph"app:layout_constraintTop_toTopOf="parent"app:layout_constraintBottom_toTopOf="@id/bottom_nav"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent" /><com.google.android.material.bottomnavigation.BottomNavigationViewandroid:id="@+id/bottom_nav"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_gravity="start"app:menu="@menu/bottom_nav_menu"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout></androidx.drawerlayout.widget.DrawerLayout>

BottomNavigationView菜单

res/menu目录中创建bottom_nav_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:id="@+id/newsListFragment"android:icon="@drawable/ic_news"android:title="News" /><itemandroid:id="@+id/userProfileFragment"android:icon="@drawable/ic_profile"android:title="Profile" />
</menu>

主Activity

MainActivity.kt中设置NavControllerBottomNavigationView

kotlin">class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val navController = findNavController(R.id.nav_host_fragment)val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_nav)bottomNavigationView.setupWithNavController(navController)}override fun onSupportNavigateUp(): Boolean {val navController = findNavController(R.id.nav_host_fragment)return navController.navigateUp() || super.onSupportNavigateUp()}
}

第二步:创建Fragment

新闻列表Fragment

创建NewsListFragment.kt,显示一组新闻文章。

kotlin">class NewsListFragment : Fragment(R.layout.fragment_news_list) {override fun onViewCreated(view: View, savedInstanceState: Bundle?) {super.onViewCreated(view, savedInstanceState)val navController = findNavController()// 示例数据val articles = listOf("Article 1", "Article 2", "Article 3")val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, articles)view.findViewById<ListView>(R.id.newsListView).adapter = adapterview.findViewById<ListView>(R.id.newsListView).setOnItemClickListener { _, _, position, _ ->val action = NewsListFragmentDirections.actionNewsListFragmentToNewsDetailFragment(position)navController.navigate(action)}}
}

新闻详情Fragment

创建NewsDetailFragment.kt,显示选定新闻文章的详细信息。

kotlin">class NewsDetailFragment : Fragment(R.layout.fragment_news_detail) {override fun onViewCreated(view: View, savedInstanceState: Bundle?) {super.onViewCreated(view, savedInstanceState)val args: NewsDetailFragmentArgs by navArgs()val articleId = args.articleIdview.findViewById<TextView>(R.id.articleTextView).text = "Displaying details for article $articleId"}
}

用户资料Fragment

创建UserProfileFragment.kt,显示用户的资料信息。

kotlin">class UserProfileFragment : Fragment(R.layout.fragment_user_profile) {override fun onViewCreated(view: View, savedInstanceState: Bundle?) {super.onViewCreated(view, savedInstanceState)// 示例用户信息view.findViewById<TextView>(R.id.userNameTextView).text = "John Doe"view.findViewById<TextView>(R.id.userEmailTextView).text = "john.doe@example.com"}
}

第三步:运行和测试

现在,我们已经完成了所有必要的步骤,可以运行应用程序并测试导航功能。

  • 启动应用程序,底部导航栏将显示新闻列表和用户资料页面。
  • 在新闻列表页面,点击任意文章将导航到新闻详情页面,并显示选定文章的详细信息。
  • 点击底部导航栏中的用户资料图标,将导航到用户资料页面,显示用户的相关信息。

结论

通过这个实践案例,我们展示了如何使用Jetpack Navigation创建一个简单的新闻应用。我们涵盖了设置导航图、在Fragment之间导航、传递数据、处理返回操作以及集成底部导航。Jetpack Navigation提供了强大且灵活的解决方案,使得管理复杂的导航场景变得更加简单和高效。

Best regards!


http://www.ppmy.cn/server/53113.html

相关文章

【Android】设置光标颜色和图标

创建主题 该主题可以更改文字下方拖拽手柄的颜色 <?xml version"1.0" encoding"utf-8"?> <resources><style name"RedTextCursor"><item name"android:colorControlActivated">#FF0000</item></…

使用Python进行自然语言处理:从基础到实战

使用Python进行自然语言处理:从基础到实战 自然语言处理(Natural Language Processing, NLP)是人工智能的重要领域,旨在处理和分析自然语言数据。Python凭借其丰富的库和社区支持,成为NLP的首选编程语言。本文将介绍自然语言处理的基础概念、常用的Python库以及一个实战项…

kylin v10 离线安装chrome centos离线安装chrome linux离线安装谷歌浏览器

1. 先用自己联网的计算机&#xff0c;下载离线安装包&#xff0c;浏览器输入链接下载安装包&#xff1a; https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm 1.2. 信创环境不用执行下面&#xff0c;因为没网 1.3. 若为阿里云服务器&#xff0c;或服…

Hive基础教程

文章目录 Apache Hive 教程1. Hive-简介1.1 学习Hive的前置知识1.2 什么是Hive&#xff1f;1.3 Hive的架构1.4 Hive的工作流程 Apache Hive 教程 资料来源&#xff1a;Hive Tutorial (tutorialspoint.com) Hive是Hadoop中用于处理结构化数据的数据仓库基础设施工具。它驻留在H…

Web渗透:文件上传-后端过滤

在上一篇文件上传的内容中笔者阐述了文件上传漏洞产生的相关原理以及使用了一个pikachu靶场的例子进行演示&#xff0c;在这个例子中涉及到了前端代码对于文件上传漏洞的相关防护&#xff0c;以及站在攻击者的角度我们要如何绕过前端的防护成功进行攻击&#xff1b;但是事实上对…

动手学深度学习(Pytorch版)代码实践 -卷积神经网络-22池化层

22池化层 import torch from torch import nn# 最大汇聚层和平均汇聚层 def pool2d(X, pool_size, modemax):p_h, p_w pool_sizeY torch.zeros((X.shape[0] - p_h 1, X.shape[1] - p_w 1))for i in range(Y.shape[0]):for j in range(Y.shape[1]):if mode max:Y[i, j] X…

macOS 环境下 MySQL Server 启动命令

MySQL Community Server for macOS 下载&#xff1a; MySQL :: Download MySQL Community Server 安装后 MySQL Server 启动和关闭命令&#xff1a; 启动&#xff1a; sudo /usr/local/mysql/support-files/mysql.server start 停止&#xff1a; sudo /usr/local/mysql/support…

如何在SQL中实现多条件的LIFO查询

在SQL中实现多条件的LIFO&#xff08;后进先出&#xff09;查询&#xff0c;你需要首先明确你的“多条件”指的是什么。但通常情况下&#xff0c;你可能希望基于多个字段&#xff08;如时间戳、用户ID等&#xff09;来确定LIFO的顺序。 以下是一个基于时间戳和用户ID的示例&am…