Jetpack Navigation - 在 Fragment 中跳转到 Activity(4 种方式) - 详解

news/2025/9/20 9:25:02/文章来源:https://www.cnblogs.com/yxysuanfa/p/19102014

一、使用 startActivity 跳转

1、Fragment Layout
<?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"tools:context=".fragment.TestFragment"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="TestFragment"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><Buttonandroid:id="@+id/btn_jump"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="跳转"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
2、Activity Code
  • TestFragment.xml
public class TestFragment
extends Fragment {
public static final String TAG = TestFragment.class.
getSimpleName();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_test, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button btnJump = view.findViewById(R.id.btn_jump);
btnJump.setOnClickListener(v ->
{
Intent intent = new Intent(getActivity(), Test2Activity.class)
;
startActivity(intent);
});
}
}
3、Activity Layout
  • activity_test1.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:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".Test1Activity"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Test1Activity"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><fragmentandroid:name="com.my.navigation.fragment.TestFragment"android:layout_width="match_parent"android:layout_height="300dp"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
  • activity_test2.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:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".Test1Activity"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Test2Activity"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><Buttonandroid:id="@+id/btn_back"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="返回"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
4、Activity Code
  • Test1Activity.java
public class Test1Activity
extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_test1);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) ->
{
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
}
}
  • Test2Activity.java
public class Test2Activity
extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_test2);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) ->
{
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
Button btnBack = findViewById(R.id.btn_back);
btnBack.setOnClickListener(v ->
{
finish();
});
}
}

二、使用 Activity Result API 跳转

1、Fragment Code
ActivityResultLauncher<
Intent> activityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result ->
{
if (result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
int num = data.getIntExtra("num", 0);
Log.i(TAG, "num: " + num);
}
}
);
Button btnJump = view.findViewById(R.id.btn_jump);
btnJump.setOnClickListener(v ->
{
Intent intent = new Intent(getActivity(), Test2Activity.class)
;
activityResultLauncher.launch(intent);
});
2、Activity Code
  • Test2Activity.java
Button btnBack = findViewById(R.id.btn_back);
btnBack.setOnClickListener(v ->
{
Intent intent = new Intent();
intent.putExtra("num", 100);
setResult(RESULT_OK, intent);
finish();
});

三、使用 startActivityForResult 方法跳转

1、Fragment Code
private static final int REQUEST_CODE = 100;
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
int num = data.getIntExtra("num", 0);
Log.i(TAG, "num: " + num);
}
}
}
Button btnJump = view.findViewById(R.id.btn_jump);
btnJump.setOnClickListener(v ->
{
Intent intent = new Intent(getActivity(), Test2Activity.class)
;
startActivityForResult(intent, REQUEST_CODE);
});
2、Activity Code
  • Test2Activity.java
Button btnBack = findViewById(R.id.btn_back);
btnBack.setOnClickListener(v ->
{
Intent intent = new Intent();
intent.putExtra("num", 100);
setResult(RESULT_OK, intent);
finish();
});

四、使用 Navigation 跳转

1、Fragment Layout
<?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"tools:context=".fragment.TestFragment"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="TestFragment"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><Buttonandroid:id="@+id/btn_jump"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="跳转"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
2、Fragment Code
  • TestFragment.java
public class TestFragment
extends Fragment {
public static final String TAG = TestFragment.class.
getSimpleName();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_test, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
NavController navController = Navigation.findNavController(view);
Button btnJump = view.findViewById(R.id.btn_jump);
btnJump.setOnClickListener(v ->
{
navController.navigate(R.id.action_testFragment_to_test2Activity);
});
}
}
3、Navigation Graph
  • test_graph_navigation.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"android:id="@+id/test_graph_navigation"app:startDestination="@id/testFragment"><fragmentandroid:id="@+id/testFragment"android:name="com.my.navigation.fragment.TestFragment"android:label="fragment_test"tools:layout="@layout/fragment_test"><actionandroid:id="@+id/action_testFragment_to_test2Activity"app:destination="@id/test2Activity" />
</fragment>
<activityandroid:id="@+id/test2Activity"android:name="com.my.navigation.Test2Activity"android:label="Test2Activity" />
</navigation>
4、Activity Layout
  • activity_test1.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:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".Test1Activity"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Test1Activity"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><fragmentandroid:id="@+id/nhf"android:name="androidx.navigation.fragment.NavHostFragment"android:layout_width="match_parent"android:layout_height="300dp"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:navGraph="@navigation/test_graph_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
  • activity_test2.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:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".Test1Activity"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Test2Activity"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><Buttonandroid:id="@+id/btn_back"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="返回"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
5、Activity Code
  • Test1Activity.java
public class Test1Activity
extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_test1);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) ->
{
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
}
}
  • Test2Activity.java
public class Test2Activity
extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_test2);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) ->
{
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
Button btnBack = findViewById(R.id.btn_back);
btnBack.setOnClickListener(v ->
{
finish();
});
}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/908226.shtml

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

相关文章

PION 游击

Day -70 只有 \(70\) 天了,是时候开坑了。 做昨天模拟赛的 T4,\(n=T=3\times 10^4\) 开了 \(2s\)。 感觉 \(O(Tn)\) 可以争一下,在 CF 的原上面过了。 可爱的搬题人,CF 上面只有 \(2\times 10^4\) 而且开了 \(7s\)…

神经网络构成框架-理论学习 - 指南

神经网络构成框架-理论学习 - 指南2025-09-20 09:24 tlnshuju 阅读(0) 评论(0) 收藏 举报pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !impo…

Web3 开发者修炼全图谱:从 Web2 走向 Web3 的实用的系统性学习指南

Web3 开发者修炼全图谱:从 Web2 走向 Web3 的实用的系统性学习指南pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: &quo…

强化学习之父 Richard Sutton: 如今AI正进入“经验时代” - 指南

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

Java 注解 - 实践

Java 注解 - 实践2025-09-20 08:52 tlnshuju 阅读(0) 评论(0) 收藏 举报pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-fami…

安规对变压器的绝缘系统要求

安规对变压器的绝缘系统要求2025-09-20 08:54 斑鸠,一生。 阅读(0) 评论(0) 收藏 举报

嵌入式笔记系列——UART:TTL-UART、RS-232、RS-422、RS-485 - 指南

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

实用指南:医院高值耗材智能化管理路径分析(下)

实用指南:医院高值耗材智能化管理路径分析(下)pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas",…

Flutter应用自动更新系统:生产环境的挑战与解决方案

Flutter应用自动更新系统:生产环境的挑战与解决方案本文基于BeeCount(蜜蜂记账)项目的实际开发经验,深入探讨Android应用自动更新的完整实现,包括GitHub Releases集成、APK安装、R8混淆问题处理等核心技术难点。项目…

.NET Core中使用SignalR

.NET Core中使用SignalR基本介绍 1.什么是signalRSignalR 是微软开发的一个开源库,它可以让服务器端代码能够即时推送内容到连接的客户端,用来简化向客户端应用程序添加实时功能的过程。大白话的意思就是微软搞了一个…

Django + Vue3 前后端分离工艺实现自动化测试平台从零到有系列 <第一章> 之 注册登录完成

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

实用指南:【保姆级教程】TEXTurePaper运行环境搭建与Stable Diffusion模型本地化

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

实用指南:修复Conda连接异常:CondaHTTPError HTTP 000 CONNECTION FAILED故障排除指南

实用指南:修复Conda连接异常:CondaHTTPError HTTP 000 CONNECTION FAILED故障排除指南pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important…

高级数据结构手册

LCA //exam:P3379 【模板】最近公共祖先(LCA) #include <iostream> #include <cstdio> #include <vector> #define int long long using namespace std; const int MAXN=5e5+5,MAXM=25; void dfs…

3634501 - [CVE-2025-42944] Insecure Deserialization vulnerability in SAP Netweaver (RMI-P4)

3634501 - [CVE-2025-42944] Insecure Deserialization vulnerability in SAP Netweaver (RMI-P4)Symptom Due to a deserialization vulnerability in SAP NetWeaver, an unauthenticated attacker could exploit the…

【无人艇协同】基于matlab面向海事安全的双体无人艇分布式协同任务规划(目标函数:总时间满意度)【含Matlab源码 14161期】博士论文 - 教程

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

实用指南:Unity 打包 iOS,Xcode 构建并上传 App Store

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

实用指南:GitHub 热榜项目 - 日榜(2025-09-09)

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

深入解析:【Fiora深度解析】手把手教你用固定公网IP搭建专属聊天系统!

深入解析:【Fiora深度解析】手把手教你用固定公网IP搭建专属聊天系统!2025-09-20 08:13 tlnshuju 阅读(0) 评论(0) 收藏 举报pre { white-space: pre !important; word-wrap: normal !important; overflow-x: au…

使用JavaScript和CSS创建动态高亮导航栏

本文详细介绍了两种实现动态高亮导航栏的技术方案:第一种使用getBoundingClientRect方法精确计算元素位置和尺寸,第二种利用新兴的View Transition API简化动画实现。文章包含完整的代码示例和实际演示,适合前端开发…