安卓Fragment基礎

目錄

  • 前言
  • 一、基礎使用
  • 二、動態添加Fragment
  • 三、Fragment的生命周期
  • 四、Fragment之間進行通信
  • 五、Fragment兼容手機和平板示例


前言

Fragment基礎使用筆記

一、基礎使用

Activity布局和文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:baselineAligned="false"><fragmentandroid:id="@+id/fragment1"android:name="com.henry.FragmentTest.test1.Fragment1"android:layout_width="0dip"android:layout_height="match_parent"android:layout_weight="1" /><fragmentandroid:id="@+id/fragment2"android:name="com.henry.FragmentTest.test1.Fragment2"android:layout_width="0dip"android:layout_height="match_parent"android:layout_weight="1" /></LinearLayout>
public class fragmentactivity extends AppCompatActivity {@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_fragments);}
}

兩個Fragment布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#00ff00" ><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="This is fragment 1"android:textColor="#000000"android:textSize="25sp" /></LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#ffff00" ><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="This is fragment 2"android:textColor="#000000"android:textSize="25sp" /></LinearLayout>

Fragment文件

public class Fragment1 extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater.inflate(R.layout.fragment1, container, false);}}
public class Fragment2 extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater.inflate(R.layout.fragment2, container, false);}}

顯示:一個Activity很融洽地包含了兩個Fragment,這兩個Fragment平分了整個屏幕,效果如下:

在這里插入圖片描述


二、動態添加Fragment

activity修改布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/main_layout"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.henry.PreferenceTest.FragmentActivity"android:orientation="horizontal">
</LinearLayout>

activity動態獲取fragment

public class fragmentactivity extends AppCompatActivity {protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_fragments);Display display = getWindowManager().getDefaultDisplay();if (display.getWidth() > display.getHeight()) {Fragment1 fragment1 = new Fragment1();getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();} else {Fragment2 fragment2 = new Fragment2();getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit();}}}

步驟如下:

獲取到FragmentManager,在Activity中可以直接通過getFragmentManager得到。
開啟一個事務,通過調用beginTransaction方法開啟。
向容器內加入Fragment,一般使用replace方法實現,需要傳入容器的id和Fragment的實例。
提交事務,調用commit方法提交。

三、Fragment的生命周期

Fragment 的生命周期包括以下方法:

onAttach(): 當 Fragment 與 Activity 關聯時調用。
onCreate(): 當 Fragment 創建時調用。
onCreateView(): 創建 Fragment 的視圖層次結構時調用。
onActivityCreated(): 當與 Fragment 相關聯的 Activity 完成 onCreate() 方法后調用。
onStart(): 當 Fragment 可見時調用。
onResume(): 當 Fragment 可交互時調用。
onPause(): 當 Fragment 失去焦點但仍可見時調用。
onStop(): 當 Fragment 不再可見時調用。
onDestroyView(): 當 Fragment 的視圖層次結構被銷毀時調用。
onDestroy(): 當 Fragment 被銷毀時調用。
onDetach(): 當 Fragment 與 Activity 解除關聯時調用。

下面是 Fragment 生命周期方法的執行順序:

當 Fragment 被添加到 Activity 時,依次執行 onAttach()、onCreate()、onCreateView()、onActivityCreated()、onStart()、onResume()。
當 Activity 進入后臺或另一個 Fragment 覆蓋當前 Fragment 時,依次執行 onPause()、onStop()。
當 Activity 回到前臺或當前 Fragment 重新獲得焦點時,依次執行 onStart()、onResume()。
當 Fragment 被移除或 Activity 被銷毀時,依次執行 onPause()、onStop()、onDestroyView()、onDestroy()、onDetach()。

四、Fragment之間進行通信

activity回到示例一中,包含兩個fragment。

修改fragment2.xml,添加一個按鈕:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:background="#ffff00" ><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="This is fragment 2"android:textColor="#000000"android:textSize="25sp" /><Buttonandroid:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Get fragment1 text"/></LinearLayout>

fragment1.xml,為TextView添加一個id

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#00ff00" ><TextViewandroid:id="@+id/fragment1_text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="This is fragment 1"android:textColor="#000000"android:textSize="25sp" /></LinearLayout>

修改Fragment2.java,添加onActivityCreated方法,并處理按鈕的點擊事件:

public class Fragment2 extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater.inflate(R.layout.fragment2, container, false);}@Overridepublic void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);Button button = (Button) getActivity().findViewById(R.id.button);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {TextView textView = (TextView) getActivity().findViewById(R.id.fragment1_text);Toast.makeText(getActivity(), textView.getText(), Toast.LENGTH_LONG).show();}});}
}

運行程序,點擊一下fragment2上的按鈕,效果如下

在這里插入圖片描述

getActivity方法可以讓Fragment獲取到關聯的Activity,然后再調用Activity的findViewById方法,就可以獲取到和這個Activity關聯的其它Fragment的視圖了。

Fragment 之間還可以通過以下幾種方式進行通信:

  • 通過 Activity:Fragment 可以通過與 Activity 通信來實現 Fragment 之間的通信。Fragment 可以通過 getActivity() 方法獲取關聯的 Activity,并通過 Activity 的方法或接口來傳遞數據或事件。
  • 直接調用其他 Fragment 的方法:如果一個 Fragment 持有對另一個 Fragment 的引用,可以直接調用另一個 Fragment 的公共方法來進行通信。這種方式適用于兩個 Fragment 之間存在直接的關聯關系的情況。
  • 使用 Bundle:可以通過設置 Fragment 的參數(通過 setArguments() 方法)來傳遞數據,在另一個 Fragment 中通過 getArguments() 方法獲取數據。這種方式適用于需要在 Fragment 創建時傳遞數據的情況。
  • 使用接口回調:定義一個接口,在一個 Fragment 中實現該接口并在另一個 Fragment 中持有該接口的引用。通過接口回調的方式,一個 Fragment 可以調用另一個 Fragment 實現的接口方法來進行通信。
  • 使用廣播:通過發送廣播來實現 Fragment 之間的通信。一個 Fragment 發送廣播,另一個 Fragment 注冊廣播接收器來接收廣播消息。這種方式適用于需要跨組件通信的情況。
  • 使用共享 ViewModel:使用 Architecture Components 中的 ViewModel 來實現 Fragment 之間的通信。多個 Fragment 可以通過共享同一個 ViewModel 實例來共享數據和狀態。

五、Fragment兼容手機和平板示例

核心在于實現兩個activity_main布局文件,一個是res/layout,另一個在res/layout-land
Android系統又會根據當前的運行環境判斷程序是否運行在大屏幕設備上,如果運行在大屏幕設備上,就加載layout-land目錄下的activity_main.xml,否則就默認加載layout目錄下的activity_main.xml。

res/layout/activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="horizontal"tools:context=".MainActivity"><fragmentandroid:id="@+id/menu_fragment"android:name="com.henry.FragmentTest.test1.MenuFragment"android:layout_width="fill_parent"android:layout_height="fill_parent" /></LinearLayout>

在這里插入圖片描述

res/layout-land/activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="horizontal"android:baselineAligned="false"tools:context=".MainActivity"><fragmentandroid:id="@+id/left_fragment"android:name="com.henry.FragmentTest.test1.MenuFragment"android:layout_width="0dip"android:layout_height="fill_parent"android:layout_weight="1"/><FrameLayoutandroid:id="@+id/details_layout"android:layout_width="0dip"android:layout_height="fill_parent"android:layout_weight="3"></FrameLayout></LinearLayout>

在這里插入圖片描述

fragmentactivity.java

public class fragmentactivity extends AppCompatActivity {protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_fragments);}}

MenuFragment.java

public class MenuFragment extends Fragment implements AdapterView.OnItemClickListener {/*** 菜單界面中只包含了一個ListView。*/private ListView menuList;/*** ListView的適配器。*/private ArrayAdapter<String> adapter;/*** 用于填充ListView的數據,這里就簡單只用了兩條數據。*/private String[] menuItems = {"Sound", "Display"};/*** 是否是雙頁模式。如果一個Activity中包含了兩個Fragment,就是雙頁模式。*/private boolean isTwoPane;/*** 當Activity和Fragment建立關聯時,初始化適配器中的數據。*/@Overridepublic void onAttach(Activity activity) {super.onAttach(activity);adapter = new ArrayAdapter<String>(activity, android.R.layout.simple_list_item_1, menuItems);}/*** 加載menu_fragment布局文件,為ListView綁定了適配器,并設置了監聽事件。*/@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {View view = inflater.inflate(R.layout.menu_fragment, container, false);menuList = (ListView) view.findViewById(R.id.menu_list);menuList.setAdapter(adapter);menuList.setOnItemClickListener(this);return view;}/*** 當Activity創建完畢后,嘗試獲取一下布局文件中是否有details_layout這個元素,如果有說明當前* 是雙頁模式,如果沒有說明當前是單頁模式。*/@Overridepublic void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);if (getActivity().findViewById(R.id.details_layout) != null) {isTwoPane = true;} else {isTwoPane = false;}}/*** 處理ListView的點擊事件,會根據當前是否是雙頁模式進行判斷。如果是雙頁模式,則會動態添加Fragment。* 如果不是雙頁模式,則會打開新的Activity。*/@Overridepublic void onItemClick(AdapterView<?> arg0, View view, int index, long arg3) {if (isTwoPane) {Fragment fragment = null;if (index == 0) {fragment = new SoundFragment();} else if (index == 1) {fragment = new DisplayFragment();}getFragmentManager().beginTransaction().replace(R.id.details_layout, fragment).commit();} else {Intent intent = null;if (index == 0) {intent = new Intent(getActivity(), SoundActivity.class);} else if (index == 1) {intent = new Intent(getActivity(), DisplayActivity.class);}startActivity(intent);}}}

使用了ArrayAdapter初始化ListView

menu_fragment.xml

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"><ListViewandroid:id="@+id/menu_list"android:layout_width="fill_parent"android:layout_height="fill_parent"></ListView></LinearLayout>

SoundFragment.java

public class SoundFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {View view = inflater.inflate(R.layout.sound_fragment, container, false);return view;}}

對應的布局文件

<?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"android:background="#00ff00"android:orientation="vertical" ><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerInParent="true"android:textSize="28sp"android:textColor="#000000"android:text="This is sound view"/></RelativeLayout>

DisplayFragment.java

public class DisplayFragment extends Fragment {public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {View view = inflater.inflate(R.layout.display_fragment, container, false);return view;}
}

對應的布局文件

<?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"android:background="#0000ff"android:orientation="vertical" ><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerInParent="true"android:textSize="28sp"android:textColor="#000000"android:text="This is display view"/>
</RelativeLayout>

SoundActivity.java

public class SoundActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.sound_activity);}}

對應的布局,SoundFragment

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/sound_fragment"android:name="com.henry.FragmentTest.test1.SoundFragment"android:layout_width="match_parent"android:layout_height="match_parent" ></fragment>

DisplayFragment

public class DisplayFragment extends Fragment {public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {View view = inflater.inflate(R.layout.display_fragment, container, false);return view;}
}

對應的布局,DisplayFragment

<?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"android:background="#0000ff"android:orientation="vertical" ><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerInParent="true"android:textSize="28sp"android:textColor="#000000"android:text="This is display view"/></RelativeLayout>

手機上顯示:

在這里插入圖片描述

平板上顯示:

在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/13216.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/13216.shtml
英文地址,請注明出處:http://en.pswp.cn/web/13216.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

OpenAI 發布 GPT-4o,再次鞏固行業地位!

5 月 14 日凌晨 1 點&#xff08;太平洋時間上午 10 點&#xff09;&#xff0c;OpenAI 發布了其最新的 GPT-4o&#xff0c;再次鞏固了其在人工智能領域的領導地位。這次發布不僅僅是一個產品的推出&#xff0c;更是向世界宣告 AI 技術已邁入一個全新的紀元。OpenAI 的 CEO 薩姆…

品牌竄貨治理管控的方法

竄貨問題確實是一個需要品牌方高度關注和有效治理的難題。這種現象通常源于品牌區域銷售政策的差異&#xff0c;經銷商為了獲取更多的利潤&#xff0c;往往會利用這些差異進行跨區域的低價銷售。這不僅損害了大多數經銷商的利益&#xff0c;也破壞了市場的穩定和品牌價值。 品牌…

深入理解 Spring 循環依賴之三級緩存(附源碼分析)

前言&#xff1a; 學過 Spring 的都知道 Spring 利用三級緩存解決了循環依賴問題&#xff0c;那你知道什么是循環依賴&#xff1f;什么又是三級緩存&#xff1f;本篇將從源碼層面分析 Spring 是怎么去利用三級緩存幫我們解決循環依賴問題。 深入理解 Spring IOC 底層實現機制…

三生隨記——麗水詭事

在浙江的深山之中&#xff0c;隱藏著一座名為麗水的古老小城。這里山水秀麗&#xff0c;風景如畫&#xff0c;但在這美麗的外表下&#xff0c;卻隱藏著不為人知的恐怖秘密。 傳聞&#xff0c;麗水的郊外有一片被詛咒的竹林。這片竹林與其他竹林不同&#xff0c;它的葉子常年枯黃…

c# datagridview基本操作,包括行拖拽,添加自定義行列。

項目場景&#xff1a; 這段代碼定義了一個名為 ucDatagridviewHelper 的用戶控件&#xff08;UserControl&#xff09;&#xff0c;該控件包含了一個 DataGridView 控件和一些其他功能。 這段代碼的主要部分&#xff1a; 構造函數&#xff1a;在構造函數中&#xff0c;初始化…

C++ | Leetcode C++題解之第89題格雷編碼

題目&#xff1a; 題解&#xff1a; class Solution { public:vector<int> grayCode(int n) {vector<int> ret(1 << n);for (int i 0; i < ret.size(); i) {ret[i] (i >> 1) ^ i;}return ret;} };

數據結構--紅黑樹(RBTree)

一、紅黑樹概念 1.1 什么是紅黑樹 紅黑樹&#xff0c;是一種二叉搜索樹&#xff0c;但在每個結點上增加一個存儲位表示結點的顏色&#xff0c;可以是Red或 Black。 通過對任何一條從根到葉子的路徑上各個結點著色方式的限制&#xff0c;紅黑樹確保沒有一條路徑會比其他路徑長…

openEuler-22.03-LTS安裝opengauss5.0.1(包含cm集群管理)主備

環境說明 openEuler-22.0.3-LTS opengauss5.0.1 安裝數據庫 安裝系統依賴包 yum -y install lksctp* yum -y install psmisc yum -y install bzip2 yum -y install unzip yum -y install gcc yum -y install gcc-c yum -y install perl yum -y install libxml2-devel yum …

前端(包含cocosCreator)開發環節調取后端接口時跨域,解決辦法之反向代理

/** eslint-disable */ var http require(http),httpProxy require(http-proxy),HttpProxyRules require(http-proxy-rules);// Set up proxy rules instance var port 9090 var proxyRules new HttpProxyRules({rules: {/api/(.*): https://baidu.com/$1, // 測試環境游戲…

自學VBA 設置單元格文字格式 筆記

一.設定對應單元格對應需要顯示的格式 Cells(1, 1).Font.Size 18 字體大小 Cells(1, 2).Font.Color RGB(255, 0, 0) 字體顏色 Cells(1, 3).Font.Name "黑體" 字體類型 Cells(1, 4).Font.Italic True 字體斜體 Cells(1, 5).Font.FontStyle "BOLD"…

ubuntu下gcc編譯器的安裝

.gcc編譯器的安裝 一般linux下是覆蓋含有的&#xff0c;如果沒有執行更新命令 sudo apt update gcc安裝成功&#xff0c;可以檢查一下版本 可以看出我的gcc是9.4.0版本的

驗證torch.nn.Conv2d

import os import cv2 import torch import numpy as np import random import cv2 as cv from matplotlib import pyplot as pltdef f_VerifyConv2D():"""驗證torch.nn.Conv2d&#xff0c; 并將輸入數據及權重保存到txt文件中"""x torch.randn…

SpringBoot環境隔離Profiles

前言 通常我們開發不可能只有一個生產環境&#xff0c;還會有其它的開發&#xff0c;測試&#xff0c;預發布環境等等。為了更好的管理每個環境的配置項&#xff0c;springboot也提供了對應的環境隔離的方法。 直接上干貨 知識點 激活環境方法 1&#xff0c;在application…

專用設備制造業供應商收發文件,有什么專業而輕便的方式嗎?

專用設備制造業的特點包括&#xff1a;門類廣、跨度大、科技含量高。它主要生產的是國民經濟各部門&#xff08;包括采掘、化工、冶煉、能源、醫療衛生、環保等&#xff09;所急需的重大成套設備&#xff0c;例如礦產資源井采及露天開采設備、大型火電、水電、核電成套設備、石…

教育行業文本短信VS視頻短信VS語音短信哪個好?

在教育行業中&#xff0c;文本短信、視頻短信和語音短信各有其優勢&#xff0c;選擇哪種方式更好取決于具體的應用場景和目標。 文本短信的優勢在于&#xff1a; 1.簡潔明了&#xff1a;能夠快速、直接地傳遞信息&#xff0c;對于需要快速通知或提醒的場景非常適用。 …

通過內網穿透免費部署我們的springboot+vue項目 實現跟服務器一樣的效果

前文講到通過內網穿透能夠實現遠程訪問個人電腦的靜態資源。本文將講解通過內網穿透實現遠程訪問本地的項目&#xff0c;實現跟部署到服務器一樣的效果&#xff1a;前文鏈接&#xff1a;通過內網穿透實現遠程訪問個人電腦資源詳細過程&#xff08;免費&#xff09;&#xff08;…

深度學習之卷積神經網絡理論基礎

深度學習之卷積神經網絡理論基礎 卷積層的操作&#xff08;Convolutional layer&#xff09; 在提出卷積層的概念之前首先引入圖像識別的特點 圖像識別的特點 特征具有局部性&#xff1a;老虎重要特征“王字”僅出現在頭部區域特征可能出現在任何位置下采樣圖像&#xff0c…

Python 小抄

Python 備忘單 目錄 1.語法和空格 2.注釋 3.數字和運算 4.字符串處理 5.列表、元組和字典 6.JSON 7.循環 8.文件處理 9.函數 10.處理日期時間 11.NumPy 12.Pandas 要運行單元格&#xff0c;請按 ShiftEnter 或單擊頁面頂部的 Run&#xff08;運行&#xff09;。 1.語法和空格…

三種方法進行跨服務器文件傳輸

今天需要在一個centOS服務器上編譯一個工具, 我的本地主機是ubuntu, 但是由于服務器是合規環境, 沒有文件傳輸的接口, 也不能訪問github等外網, 所以很多依賴只能下載到ubuntu然后在想辦法搞到服務器上. 這種場景有三種簡單有用的辦法, 整理一下. 方法一: 把主機配置成http ser…

6---Linux下版本控制器Git的知識點

一、Linux之父與Git的故事&#xff1a; Linux之父叫做“Linus Torvalds”&#xff0c;我們簡稱為雷納斯。Linux是開源項目&#xff0c;所以在Linux的早期開發中&#xff0c;許多世界各地的能力各異的程序員都參與到Linux的項目開發中。那時&#xff0c;雷納斯每天都會收到許許…