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

news2024/9/21 16:22:02

在这里插入图片描述

在这个实践案例中,我们将使用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">

    <fragment
        android:id="@+id/newsListFragment"
        android:name="com.example.newsapp.NewsListFragment"
        android:label="News List"
        tools:layout="@layout/fragment_news_list" >
        <action
            android:id="@+id/action_newsListFragment_to_newsDetailFragment"
            app:destination="@id/newsDetailFragment" />
        <action
            android:id="@+id/action_newsListFragment_to_userProfileFragment"
            app:destination="@id/userProfileFragment" />
    </fragment>

    <fragment
        android:id="@+id/newsDetailFragment"
        android:name="com.example.newsapp.NewsDetailFragment"
        android:label="News Detail"
        tools:layout="@layout/fragment_news_detail" >
        <argument
            android:name="articleId"
            app:argType="integer" />
    </fragment>

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

        <fragment
            android: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.BottomNavigationView
            android: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">
    <item
        android:id="@+id/newsListFragment"
        android:icon="@drawable/ic_news"
        android:title="News" />
    <item
        android:id="@+id/userProfileFragment"
        android:icon="@drawable/ic_profile"
        android:title="Profile" />
</menu>

主Activity

MainActivity.kt中设置NavControllerBottomNavigationView

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,显示一组新闻文章。

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 = adapter

        view.findViewById<ListView>(R.id.newsListView).setOnItemClickListener { _, _, position, _ ->
            val action = NewsListFragmentDirections.actionNewsListFragmentToNewsDetailFragment(position)
            navController.navigate(action)
        }
    }
}

新闻详情Fragment

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

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.articleId

        view.findViewById<TextView>(R.id.articleTextView).text = "Displaying details for article $articleId"
    }
}

用户资料Fragment

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

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.coloradmin.cn/o/1870013.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

前端 Array.sort() 源码学习

源码地址 V8源码Array 710行开始为sort()相关 Array.sort()方法是那种排序呢&#xff1f; 去看源码主要是源于这个问题 // In-place QuickSort algorithm. // For short (length < 22) arrays, insertion sort is used for efficiency.源码中的第一句话就回答了我的问题…

Python第三方库GDAL 安装

安装GDAL的方式多种&#xff0c;包括pip、Anaconda、OSGeo4W等。笔者在安装过程中&#xff0c;唯独使用pip安装遇到问题。最终通过轮子文件&#xff08;.whl&#xff09;成功安装。 本文主要介绍如何下载和安装较新版本的GDAL轮子文件。 一、GDAL轮子文件下载 打开Github网站…

【Java Web】Element-plus组件库

目录 一、Element-plus组件库概述 二、Element-plus组件库基本用法 一、Element-plus组件库概述 Element-plus组件库是由饿了么团队基于Vue3框架编写的前端UI设计组件库。通俗点讲就是将用户页面设计所需的按钮、表格、导航栏等前端代码编写生成的组件元素都封装好了、用户在进…

40.设计HOOK引擎的好处

免责声明&#xff1a;内容仅供学习参考&#xff0c;请合法利用知识&#xff0c;禁止进行违法犯罪活动&#xff01; 上一个内容&#xff1a;39.右键弹出菜单管理游戏列表 以 39.右键弹出菜单管理游戏列表 它的代码为基础进行修改 效果图&#xff1a; 实现步骤&#xff1a; 首…

elk对于集群实例的日志的整合-基于logstash采集日志

说明&#xff1a;基于logstash采集日志 环境&#xff1a; 物理机192.168.31.151 一.启动2个测试实例&#xff0c;每5-10s随机生成一条订单日志 实例一 包位置&#xff1a;/home/logtest/one/log-test-0.0.1-SNAPSHOT.jar 日志位置:/docker/elastic/logstash_ingest_data/l…

《2024年新生代妈妈真实孕育状态洞察报告》

专注于行业分析与市场研究的专业机构易观分析,正式发布了其最新研究成果——《2024年新生代妈妈真实孕育状态洞察报告》。该报告深入探讨了新生代妈妈在孕育过程中的实际需求与挑战,通过对母婴行业的市场规模、消费行为、用户触媒习惯、用户关怀以及特定品类场景的细致分析,揭示…

easyui的topjui前端框架使用指南

博主今天也是第一次点开easyui的商业搜权页面&#xff0c;之前虽然一直在使用easyui前端框架&#xff08;easyui是我最喜欢的前端ui框架&#xff09;&#xff0c;但是都是使用的免费版。 然后就发现了easyui的开发公司居然基于easyui开发出了一个新的前端框架&#xff0c;于是我…

PLM系统选购指南:哪款品牌最适合你?

在选购PLM&#xff08;Product Lifecycle Management&#xff09;系统时&#xff0c;选择最适合自己企业的品牌至关重要。以下是一份清晰的PLM系统选购指南&#xff0c;帮助您根据企业的具体需求选择最合适的品牌&#xff1a; 1、明确企业需求&#xff1a; 首先&#xff0c;明…

数学建模--lingo解决线性规划问题~~灵敏度分析的认识

目录 1.线性规划问题举隅 &#xff08;1&#xff09;问题介绍 &#xff08;2&#xff09;问题分析 &#xff08;3&#xff09;灵敏度分析 &#xff08;4&#xff09;方法缺陷 &#xff08;5&#xff09;可行域&凸集 2.lingo的简单认识 &#xff08;1&#xff09;默认…

VSCode常用的一些插件

Chinese (Simplified) 汉语&#xff08;简体&#xff09;拓展包。 Auto Close Tag 可以自动增加xml/html的闭合标签。 CodeSnap 截图神器。截图效果在下面。 Dracula Official vscode一个很好看的主题。 Git Graph git管理工具。 GitHub Repositories 有了它&#xff0c;不…

C++02 变量和基本类型

基本类型 字、字节、bit、Byte之间的关系 字 word 字节 Byte 位 bit 1字 2字节 <---> 1word 2Byte 1字节 8位 <---> 1Byte 8bit 1Byte 8bits 1KB 1024Bytes 1MB 1024KB 1GB 1024MB #include <iostream> using namespace std; int main() {/*字符…

手把手教你打造高精度STM32数字时钟,超详细步骤解析

STM32数字时钟项目详解 1. 项目概述 STM32数字时钟是一个集成了时间显示、闹钟功能、温湿度检测等多功能于一体的小型电子设备。它利用STM32的实时时钟(RTC)功能作为核心,配合LCD显示屏、按键输入、温湿度传感器等外设,实现了一个功能丰富的数字时钟系统。 2. 硬件组成 STM…

腾讯云对象存储cors错误处理

最近将公司的域名进行了修改&#xff0c;同时将腾讯云的对象存储改成了https&#xff0c;为了安全嘛。然后上传软件包的时候发现上传软件就失败了。 在浏览器中打开该 HTML 文件&#xff0c;单击 Test CORS 发送请求后&#xff0c;出现以下错误&#xff0c;错误提示&#xff1…

【Java Web】PostMan业务接口测试工具

目录 一、PostMan概述 二、如何安装Postman 三、Postman的基本使用 一、PostMan概述 在生产环境中&#xff0c;一个项目在开发之前、前后端开发工程师通常需要商讨在前后端数据交互时需要采用什么样的规范格式&#xff0c;如&#xff1a;前端向后端发送请求的uri、请求和响…

【索引】数据库索引之散列索引

目录 1、什么是散列&#xff1f; 2、如何评价一个散列函数的好坏&#xff1f; 3、散列中的桶溢出处理 4、散列在索引中的应用 4、顺序索引和散列索引的比较 1、什么是散列&#xff1f; 顺序文件组织的一个缺点是我们必须访问索引结构来定位数据&#xff0c;或者必须使用二…

datax入门(datax的安装与简单使用)——01

datax入门&#xff08;datax的安装与简单使用&#xff09;——01 1. 官网2. 工具部署&#xff08;通过下载DataX工具包&#xff09;2.1 下载、解压2.2 配置2.2.1 查看配置模版2.2.2 根据模版配置json2.2.3 启动DataX 3. datax的简单使用3.1 mysql2stream3.2 mysql2mysql3.2.1 拼…

HTML【重点标签】

一、列表标签 1.无序列表 父级别&#xff1a; 无序列表的标题 ----表示无序列表的整体&#xff0c;用于包裹li标签 子级别&#xff1a; 无序列表一行的内容 ----表示无序列表的每一项&#xff0c;用于包含一行的内容 语义&#xff1a;构建没有顺序的列表 特点&#xff1a;列…

php聚合快递寄快递小程序

一、引言&#xff1a;告别传统寄件&#xff0c;拥抱便捷新选择 在数字化时代&#xff0c;我们越来越追求便捷和高效。传统的寄件方式已经无法满足现代人快速、便捷的需求。因此&#xff0c;一款聚合快递优惠寄件小程序应运而生&#xff0c;它集合了多家快递公司&#xff0c;为…

Linux高级编程——进程

1.进程的含义? 进程是一个程序执行的过程&#xff0c;会去分配内存资源&#xff0c;cpu的调度 PID, 进程标识符 当前工作路径 chdir umask 0002 进程打开的文件列表 文件IO中有提到 &#xff08;类似于标准输入 标准输出的编号&#xff0c;系统给0&#xff0c;1&#xf…

台灯的功能作用有哪些?分享好用的护眼灯!看完就知道台灯怎么选

在当今时代&#xff0c;学生们长时间地沉浸于平板、手机、电脑等电子设备中&#xff0c;这些设备的屏幕往往伴随着频闪和蓝光辐射&#xff0c;这无疑对视力健康构成了潜在威胁。家长们日益关注孩子的护眼养眼问题&#xff0c;因为视力疲劳和眼部疾病不仅会降低个体的生活质量&a…