Fragment的四種跳轉方式

来源:https://www.cnblogs.com/xlr03/archive/2022/09/27/16735358.html
-Advertisement-
Play Games

本文主要記錄了關於fragment的四種跳轉方式: 1、從同一個Activiy的一個Fragment跳轉到另外一個Fragment 2、從一個Activity的Fragment跳轉到另外一個Activity 3、從一個Activity跳轉到另外一個Activity的Fragment上4、從一個Act ...


本文主要記錄了關於fragment的四種跳轉方式:  

1、從同一個Activiy的一個Fragment跳轉到另外一個Fragment
2、從一個Activity的Fragment跳轉到另外一個Activity
3、從一個Activity跳轉到另外一個Activity的Fragment上
4、從一個Activity的Fragment跳轉到另外一個Activity的Fragment上

 

寫這篇文章只是一個簡單的記錄,當初我學這裡的時候看別人的文章總是覺得雲里霧裡的,後來自己也覺得差不多可以了,於是寫下這篇博客,也是記錄自己的學習過程。

首先新建一個項目,然後新建兩個活動MainActivity、OtherActivity。
在MainActivity的佈局文件中寫一個子佈局:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent">
 6  
 7  
 8     <FrameLayout
 9         android:id="@+id/fragment_container"
10         android:layout_width="match_parent"
11         android:layout_height="0dp"
12         android:layout_weight="1"/>
13  
14  
15 </LinearLayout>

新建一個my_fragment.xml佈局與MyFragment類

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent">
 6  
 7     <TextView
 8         android:layout_width="match_parent"
 9         android:layout_height="wrap_content"
10         android:text="MyFragment"
11         android:textSize="40sp"
12         android:gravity="center_horizontal"/>
13  
14     <Button
15         android:id="@+id/my_button"
16         android:layout_width="wrap_content"
17         android:layout_height="wrap_content"
18         android:textAllCaps="false"
19         android:text="To YourFragment"/>
20  
21     <Button
22         android:id="@+id/my_other"
23         android:layout_width="wrap_content"
24         android:layout_height="wrap_content"
25         android:textAllCaps="false"
26         android:text="To OtherActivity"/>
27  
28 </LinearLayout>

MyFragment類就暫時省略了,後面會貼出所有代碼。
在MainActivity中先添加進一個Fragment進行最開始的展示(壓棧式添加)

 1 public class MainActivity extends AppCompatActivity {
 2  
 3     @Override
 4     protected void onCreate(Bundle savedInstanceState) {
 5         super.onCreate(savedInstanceState);
 6         setContentView(R.layout.activity_main);
 7         getSupportFragmentManager()
 8                 .beginTransaction()
 9                 .replace(R.id.fragment_container,new MyFragment())
10                 .addToBackStack(null)
11                 .commit();
12  
13     }
14 }

從同一個Activiy的一個Fragment跳轉到另外一個Fragment

這個跳轉與上面初始顯示Fragment類似。
新建your_fragment.xml佈局與YourFragment類。

 1 public class YourFragment extends Fragment {
 2     public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
 3         View contentView;
 4         contentView = inflater.inflate(R.layout.your_fragment, container, false);
 5         return contentView;
 6     }
 7  
 8     @Override
 9     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
10         super.onActivityCreated(savedInstanceState);
11         Button myReturn = (Button) getActivity().findViewById(R.id.my_return);
12         myReturn.setOnClickListener(new View.OnClickListener() {
13             //返回到上一個Fragment(同一個Activity中)
14             @Override
15             public void onClick(View v) {
16                 getActivity().getSupportFragmentManager().popBackStack();
17             }
18         });
19     }
20 }

your_fragment.xml就暫時先省略了,最後會貼出全部代碼。

跳轉部分代碼如下,通過點擊按鈕跳轉:

 1 myButton.setOnClickListener(new View.OnClickListener() {
 2             @Override
 3             public void onClick(View v) {
 4                 /* 一、從同一個Activity的一個Fragment跳到另外一個Fragment*/
 5                 //壓棧式跳轉
 6                 getActivity().getSupportFragmentManager()
 7                         .beginTransaction()
 8                         .replace(R.id.fragment_container, new YourFragment(), null)
 9                         .addToBackStack(null)
10                         .commit();
11  
12             }
13         });

從一個Activity的Fragment跳轉到另外一個Activity

此跳轉與Activity之間的跳轉十分相似,只要引用上下文的時候,改成getActivity()即可。

跳轉關鍵代碼:

 1 myOther.setOnClickListener(new View.OnClickListener() {
 2             /*
 3              二、從一個Activity的Fragment跳轉到另外一個Activity(等同於Activity之間的跳轉(上下文是getActivity))
 4              */
 5             @Override
 6             public void onClick(View v) {
 7                 Intent intent = new Intent(getActivity(),OtherActivity.class);
 8                 startActivity(intent);
 9             }
10         });

從一個Activity跳轉到另外一個Activity的Fragment上

我們要從OtherActivity跳轉到MainActivity的YourFragment上去:
首先,我們在OtherActivity中的跳轉事件中給MainActivity傳遞一個參數,命名為id:

 1 Intent intent = new Intent(OtherActivity.this, MainActivity.class); 2 intent.putExtra("id",1); 3 startActivity(intent); 

然後,我們在MainActivity里接收id值,對值進行判斷,如果正確進行跳轉操作:

1 int id = getIntent().getIntExtra("id", 0);
2 if (id == 1) {      
3      getSupportFragmentManager()
4        .beginTransaction()
5        .replace(R.id.fragment_container,new YourFragment())
6        .addToBackStack(null)
7        .commit(); 
8 }

從一個Activity的Fragment跳轉到另外一個Activity的Fragment上

新建other_fragment.xml佈局作為OtherActivity的一個Fragment。

這種跳轉與第三種跳轉極為類似,我們只需要將上面的

 1 Intent intent = new Intent(OtherActivity.this, MainActivity.class); 

Intent intent = new Intent(OtherActivity.this, MainActivity.class);

關鍵代碼如下:

 1 public void onActivityCreated(@Nullable Bundle savedInstanceState) {
 2         super.onActivityCreated(savedInstanceState);
 3         Button ToButton = (Button) getActivity().findViewById(R.id.to_button);
 4         ToButton.setOnClickListener(new View.OnClickListener() {
 5             
 6             @Override
 7             public void onClick(View v) {
 8                 Intent intent = new Intent(getActivity(), MainActivity.class);
 9                 intent.putExtra("id",1);
10                 startActivity(intent);
11             }
12         });
13     }

所有代碼文件

最後附上所有的代碼文件。  
MainActivity:

 1 package com.example.fragment_activity_skiptest;
 2  
 3 import android.content.Intent;
 4 import android.support.v7.app.AppCompatActivity;
 5 import android.os.Bundle;
 6 import android.view.View;
 7  
 8 public class MainActivity extends AppCompatActivity {
 9  
10     @Override
11     protected void onCreate(Bundle savedInstanceState) {
12         super.onCreate(savedInstanceState);
13         setContentView(R.layout.activity_main);
14         getSupportFragmentManager()
15                 .beginTransaction()
16                 .replace(R.id.fragment_container,new MyFragment())
17                 .addToBackStack(null)
18                 .commit();
19         int id = getIntent().getIntExtra("id", 0);
20         if (id == 1) {
21             getSupportFragmentManager()
22                     .beginTransaction()
23                     .replace(R.id.fragment_container,new YourFragment())
24                     .addToBackStack(null)
25                     .commit();
26         }
27  
28     }
29 }

MyFragment:

 1 package com.example.fragment_activity_skiptest;
 2  
 3 import android.content.Intent;
 4 import android.os.Bundle;
 5 import android.support.annotation.Nullable;
 6 import android.support.v4.app.Fragment;
 7 import android.view.LayoutInflater;
 8 import android.view.View;
 9 import android.view.ViewGroup;
10 import android.widget.Button;
11  
12  
13 public class MyFragment extends Fragment {
14  
15     public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
16         View contentView;
17             contentView = inflater.inflate(R.layout.my_fragment, container, false);
18  
19         return contentView;
20     }
21  
22     @Override
23     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
24         super.onActivityCreated(savedInstanceState);
25         Button myButton = (Button) getActivity().findViewById(R.id.my_button);
26  
27         Button myOther = (Button) getActivity().findViewById(R.id.my_other);
28         myButton.setOnClickListener(new View.OnClickListener() {
29             @Override
30             public void onClick(View v) {
31                 /** 一、從同一個Activity的一個Fragment跳到另外一個Fragment*/
32                 //壓棧式跳轉
33                 getActivity().getSupportFragmentManager()
34                         .beginTransaction()
35                         .replace(R.id.fragment_container, new YourFragment(), null)
36                         .addToBackStack(null)
37                         .commit();
38  
39             }
40         });
41         myOther.setOnClickListener(new View.OnClickListener() {
42             /**
43              二、從一個Activity的Fragment跳轉到另外一個Activity(等同於Activity之間的跳轉(上下文是getActivity))
44              */
45             @Override
46             public void onClick(View v) {
47                 Intent intent = new Intent(getActivity(),OtherActivity.class);
48                 startActivity(intent);
49             }
50         });
51     }
52 }

OtherActivity:

 1 package com.example.fragment_activity_skiptest;
 2  
 3 import android.content.Intent;
 4 import android.support.v7.app.AppCompatActivity;
 5 import android.os.Bundle;
 6 import android.view.View;
 7 import android.widget.Button;
 8  
 9 public class OtherActivity extends AppCompatActivity {
10  
11     @Override
12     protected void onCreate(Bundle savedInstanceState) {
13         super.onCreate(savedInstanceState);
14         setContentView(R.layout.activity_other);
15         Button button = (Button)findViewById(R.id.to_MainActivity_YourFragment);
16         Button button_back = (Button)findViewById(R.id.back);
17         Button button_fm = (Button)findViewById(R.id.to_OtherFragment);
18         button.setOnClickListener(new View.OnClickListener() {
19             /*從一個Activity跳轉到另外一個Activity的Fragment上
20             例如我們要從OtherActivity跳轉到MainActivity的YourFragment上去:
21             首先,我們在OtherActivity中的跳轉事件中給MainActivity傳遞一個名為id的參數:
22             然後,我們在MainActivity里接收id值,對值進行判斷,如果正確進行跳轉操作:
23             */
24             @Override
25             public void onClick(View v) {
26                 Intent intent = new Intent(OtherActivity.this, MainActivity.class);
27                 intent.putExtra("id",1);
28                 startActivity(intent);
29  
30             }
31         });
32         button_back.setOnClickListener(new View.OnClickListener() {
33             @Override
34             public void onClick(View v) {
35                 finish();
36             }
37         });
38         button_fm.setOnClickListener(new View.OnClickListener() {
39             @Override
40             public void onClick(View v) {
41                 getSupportFragmentManager()
42                         .beginTransaction()
43                         .replace(R.id.frame_container, new OtherFragment(), null)
44                         .addToBackStack(null)
45                         .commit();
46             }
47         });
48     }
49 }

OtherFragment:

package com.example.fragment_activity_skiptest;
 
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
 
 
public class OtherFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View contentView;
        contentView = inflater.inflate(R.layout.other_fragment, container, false);
        return contentView;
    }
 
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button ToButton = (Button) getActivity().findViewById(R.id.to_button);
        ToButton.setOnClickListener(new View.OnClickListener() {
            /*4、從一個Activity的Fragment跳轉到另外一個Activity的Fragment上
            這種跳轉與第三種跳轉極為類似,我們只需要將
            Intent intent = new Intent(OtherActivity.this, MainActivity.class);
            書寫在對應的Fragment中,將OtherActivity.this更改為getActivity(),其他不用改變,幾個完成跳轉.
            */
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.putExtra("id",1);
                startActivity(intent);
            }
        });
    }
}

YourFragment:

package com.example.fragment_activity_skiptest;
 
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
 
 
public class YourFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View contentView;
        contentView = inflater.inflate(R.layout.your_fragment, container, false);
        return contentView;
    }
 
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button myReturn = (Button) getActivity().findViewById(R.id.my_return);
        myReturn.setOnClickListener(new View.OnClickListener() {
            //返回到上一個Fragment(同一個Activity中)
            @Override
            public void onClick(View v) {
                getActivity().getSupportFragmentManager().popBackStack();
            }
        });
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
 
    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>
 
 
</LinearLayout>

activity_other.xml:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:id="@+id/activity_other"
 5     android:layout_width="match_parent"
 6     android:layout_height="match_parent"
 7     android:background="#d0ff05"
 8     >
 9  
10     <FrameLayout
11         android:id="@+id/frame_container"
12         android:layout_width="match_parent"
13         android:layout_height="0dp"
14         android:layout_weight="1">
15         <LinearLayout
16             android:orientation="vertical"
17             android:layout_width="match_parent"
18             android:layout_height="match_parent">
19  
20             <TextView
21                 android:layout_width="match_parent"
22                 android:layout_height="wrap_content"
23                 android:text="OtherActivity"
24                 android:textSize="50sp"
25                 android:gravity="center_horizontal"/>
26  
27             <Button
28                 android:id="@+id/to_MainActivity_YourFragment"
29                 android:layout_width="wrap_content"
30                 android:layout_height="wrap_content"
31                 android:text="To MainActivity YourFragment"
32                 android:textAllCaps="false"/>
33  
34             <Button
35                 android:id="@+id/to_OtherFragment"
36                 android:layout_width="wrap_content"
37                 android:layout_height="wrap_content"
38                 android:text="To OtherFragment"
39                 android:textAllCaps="false"/>
40  
41             <Button
42                 android:id="@+id/back"
43                 android:layout_width="wrap_content"
44                 android:layout_height="wrap_content"
45                 android:text="back"/>
46  
47         </LinearLayout>
48     </FrameLayout>
49  
50  
51  
52 </LinearLayout>

my_fragment.xml:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent">
 6  
 7     <TextView
 8         android:layout_width="match_parent"
 9         android:layout_height="wrap_content"
10         android:text="MyFragment"
11         android:textSize="40sp"
12         android:gravity="center_horizontal"/>
13  
14     <Button
15         android:id="@+id/my_button"
16         android:layout_width="wrap_content"
17         android:layout_height="wrap_content"
18         android:textAllCaps="false"
19         android:text="To YourFragment"/>
20  
21     <Button
22         android:id="@+id/my_other"
23         android:layout_width="wrap_content"
24         android:layout_height="wrap_content"
25         android:textAllCaps	   

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Redis Desktop Manager for Mac是Mac平臺上一款非常實用的Redis可視化工具。RDM支持SSL / TLS加密,SSH隧道,基於SSH隧道的TLS,為您提供了一個易於使用的GUI,可以訪問您的Redis資料庫並執行一些基本操作:將鍵視為樹,CRUD鍵,通過shell執行 ...
  • 如何能打開閱讀chm格式文件?使用CHM Reader for Mac即可直接狀態欄打開即可使用,非常方便。 詳情:iCHM Reader for Mac(chm格式文件閱讀器) iCHM Reader中文版是最終CHM(編譯的HTML幫助)文件閱讀器。可以讓你閱讀較大的CHM文檔,在mac系統中使 ...
  • 晶體結構軟體CrystalMaker for mac創建、顯示和操作各種晶體和分子結構 ,CrystalMaker Mac版便捷、靈活,能夠容易的載入結構數據並產生壯觀的,相片型的圖形,戴上紅/藍眼鏡,還可以感受立體三維畫面,親臨分子結構當中。 詳情:CrystalMaker for Mac(晶體結 ...
  • 電阻種類很多,常用的有貼片電阻、插件電阻、熱敏電阻、壓敏電阻、光敏電阻、水泥電阻、可調電阻。 可調電阻在成品的PCBA中很少見,也大多用於電路調試中試用,等電路調試完成後再換成固定阻值的電阻,起到電路參數調節的作用。水泥電阻則在調試的時候會用到更多,當做假負載來使用。 這裡說下假負載,假負載並不是電 ...
  • 準備工作 一臺Linux(Centos7為例)伺服器。 安裝Docker服務。 安裝並啟動SqlServer容器服務。 編寫Shell文件 給出一個備份的範例 #!/bin/bash #設置mssql備份目錄 folder=/var/opt/mssql/data/databack/ day=`dat ...
  • 風裡雨里,我在深圳機場等你,口說無憑,上圖! 這是一段很長的故事!以前倒也不曾提過~ 銀河證券和騰訊雲資料庫長久以來並肩作戰,情比金堅,我們的故事日前在深圳寶安機場上映 他說:做好國產化分散式改造,就用騰訊雲資料庫。 我說:做國產資料庫,我是認真的。 誕生於2007年的騰訊雲資料庫現已歷經十四年的錘 ...
  • 1 導讀 數據的一致性是數據準確的重要指標,那如何實現數據的一致性呢?本文從事務特性和事務級別的角度和大家一起學習如何實現數據的讀寫一致性。 2 一致性 1.數據的一致性:通常指關聯數據之間的邏輯關係是否正確和完整。 舉個例子:某系統實現讀寫分離,讀資料庫是寫資料庫的備份庫,小李在系統中之前錄入的學 ...
  • 開心一刻 今天,她給我打來電話 她:你明天陪我去趟醫院吧 我:怎麼了 她:我懷孕了,陪我去打胎 我:他的嗎 她:嗯 我心一沉,猶豫了片刻:生下來吧,我養! 她:他的孩子,你不配養! 我:我隨孩子姓 需求背景 最近接到一個數據遷移的需求,舊系統的數據遷移到新系統;舊系統不會再新增業務數據,業務操作都在 ...
一周排行
    -Advertisement-
    Play Games
  • MQTTnet 是一個高性能的MQTT類庫,支持.NET Core和.NET Framework。 MQTTnet 原理: MQTTnet 是一個用於.NET的高性能MQTT類庫,實現了MQTT協議的各個層級,包括連接、會話、發佈/訂閱、QoS(服務質量)等。其原理涉及以下關鍵概念: MqttCli ...
  • 在WPF中,源屬性(Source Property)指的是提供數據的屬性,通常是數據模型或者其他控制項的屬性,而目標屬性(Target Property)則是數據綁定的目標,通常是綁定到控制項的屬性,例如TextBlock的Text屬性。數據綁定將源屬性的值自動更新到目標屬性中。 主要包含以下幾個事件: ...
  • async/await 是 C# 中非同步編程的關鍵特性,它使得非同步代碼編寫更為簡單和直觀。下麵深入詳細描述了 async/await 的使用場景、優點以及一些高級使用方法,並提供了相應的實例源代碼。 使用場景: I/O 操作: 非同步編程特別適用於涉及 I/O 操作(如文件讀寫、網路請求等)的場景。在 ...
  • 使用過office的visio軟體畫圖的小伙伴都知道,畫圖軟體分為兩部分,左側圖形庫,存放各種圖標,右側是一個畫布,將左側圖形庫的圖標控制項拖拽到右側畫布,就會生成一個新的控制項,並且可以自由拖動。那如何在WPF程式中,實現類似的功能呢?今天就以一個簡單的小例子,簡述如何在WPF中實現控制項的拖拽和拖動,... ...
  • 1、Blazor Hybrid簡介 Blazor Hybrid 使開發人員能夠將桌面和移動本機客戶端框架與 .NET 和 Blazor 結合使用。在 Blazor Hybrid 應用中,Razor 組件在設備上是本機運行的。 這些組件通過本地互操作通道呈現到嵌入式 Web 視圖控制項。 組件不在瀏覽器 ...
  • 除了內置的數據集,scikit-learn還提供了隨機樣本的生成器。通過這些生成器函數,可以生成具有特定特性和分佈的隨機數據集,以幫助進行機器學習演算法的研究、測試和比較。 目前,scikit-learn庫(v1.3.0版)中有20個不同的生成樣本的函數。本篇重點介紹其中幾個具有代表性的函數。 1. ...
  • 從0到1,手把手帶你開發截圖工具ScreenCap------002實現通過文件對話框,選擇合適的文件夾,自定義預設的圖片保存位置,簡單易學 ...
  • 每次談到容器的時候,除了Docker之外,都會說起 Kubernetes,那麼什麼是 Kubernetes呢?今天就來一起學快速入門一下 Kubernetes 吧!希望本文對您有所幫助。 Kubernetes,一種用於管理和自動化雲中容器化工作負載的工具。 想象一下你有一個管弦樂隊,將每個音樂家視為 ...
  • 目錄 基本說明 安裝 Nginx 部署 VUE 前端 部署 Django 後端 Django admin 靜態文件(CSS,JS等)丟失的問題 總結 1. 基本說明 本文介紹了在 windows 伺服器下,通過 Nginx 部署 VUE + Django 前後端分離項目。本項目前端運行在 80 埠 ...
  • 從0到1,手把手帶你開發截圖工具ScreenCap------003實現最小化程式到托盤運行,- 為了方便截圖乾凈,實現最小化程式到托盤運行,簡潔,勿擾,實現最小化程式到托盤運行, 實現托盤菜單功能,實現回顯主窗體, 實現托盤開始截屏, 實現氣泡信息提示,實現托盤程式提示,實現托盤退出程式, 封裝完... ...