Android中Fragment的加载方式与数据通信详解

发布时间 - 2026-01-11 00:19:41    点击率:

一、加载方式

1. 静态加载

1.1 加载步骤

(1) 创建fragment:创建自定义Fragment类继承自Fragment类,同时将自定义Fragment类与Fragment视图绑定(将layout转换成View)

View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

inflater用于绑定Fragment的布局文件,同时将该布局转换成View对象并返回;container为Fragment的UI所在的父容器。返回值为Fragment显示的UI,若不显示,则返回null。

inflate(int resource, ViewGroup root, boolean attachToRoot)

resource为Fragment需要加载的布局文件;root为加载Fragment的父ViewGroup,也就是onCreateView传递进来的container;attachToRoot为是否返回父ViewGroup。

(2) 使用fragment:在父视图中引入fragment,静态加载必须指定name属性以及一个唯一标识符,标识符可以为id或者tag

<!--指定在layout中实例化的Fragment类,需要为“包名.类名”的完整形式-->
android:name
<!--唯一标识,id和tag可任选其一,不可两者都没有-->
android:id
android:tag

(3) 监听事件:若在父视图对应的类中设置监听事件,可以直接访问fragment中的子组件;若在Fragment的类中设置,则必须通过inflate()返回的View对象访问Fragment中的子组件(view.findViewById(id))。

1.2 简单范例

MyFragment视图:

<?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">
 <TextView
 android:id="@+id/fragment_text"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />
</LinearLayout>

MyFragment类:

public class MyFragment extends Fragment {
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 //将layout布局转换成View对象
 View view = inflater.inflate(R.layout.myfragment, container, false);
 //必须通过view对象对其子组件进行访问
 TextView textView = (TextView) view.findViewById(R.id.fragment_text);
 textView.setText("这里是fragment");
 //返回Fragment显示UI
 return view;
 }
}

引用fragment的父视图:

<?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:layout_width="match_parent"
 android:layout_height="match_parent" tools:context="com.studying.StaticFragmentActivity">
 <fragment
 android:tag="fragment"
android:name="com.joahyau.studying.MyFragment"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"/>
</LinearLayout>

父视图对应的类设置事件监听:

public class StaticFragmentActivity extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_static_fragment);
 //可直接通过findViewById访问
 findViewById(R.id.fragment_text).setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  Toast.makeText(StaticFragmentActivity.this, "点击了文本", Toast.LENGTH_SHORT).show();
  }
 });
 }
}

2. 动态加载

2.1 加载步骤

(1) 获取事务管理器:对Fragment进行的添加、移除、替换等操作,均为事务。需通过以下代码获取事务管理器,从而对fragment进行动态操作。

FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();

(2) 创建Fragment对象:创建需要加载的fragment,而后通过add或replace等方法实现动态加载。

2.2 简单范例

布局:

<?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:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
tools:context="io.github.joahyau.studying.DynamicFragmentActivity">
 <Button
 android:id="@+id/load"
 android:text="加载"
 android:layout_width="match_parent"
 android:layout_height="80dp" />
 <LinearLayout
 android:id="@+id/container"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:orientation="horizontal" />
</LinearLayout>

Java:

public class DynamicFragmentActivity extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_dynamic_fragment);
 findViewById(R.id.load).setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  //获取事务管理器
  FragmentManager fragmentManager = getFragmentManager();
  FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
  //创建fragment,并将其动态加载到id位container的布局中
  MyFragment myFragment = new MyFragment();
  fragmentTransaction.add(R.id.container, myFragment);
  //提交事务
  fragmentTransaction.commit();
  }
 });
 }
}

二、数据通信

3. Activity向Fragment传递数据

3.1 Activity向动态加载的Fragment传递数据

(1)在Activity中获取Fragment对象;

(2)创建Bundle对象并传入数据;

(3)将Bundle对象传递给Fragment对象;

(4)在Fragment中获取Bundle对象并拆包得到数据。

范例:Activity中只有一个id为send的Button,MyFragment中只有一个TextView,这里就不再放布局代码了。

Activity:

public class MainActivity extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 findViewById(R.id.send).setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  //创建Fragment对象
  MyFragment myFragment = new MyFragment();
  //创建Bundle对象并传入数据
  Bundle bundle = new Bundle();
  bundle.putString("info", "这里是向Fragment传递的数据");
  myFragment.setArguments(bundle);
  //加载Fragment
  FragmentManager fragmentManager = getFragmentManager();
  FragmentTransaction beginTransaction = fragmentManager.beginTransaction();
  beginTransaction.add(R.id.layout, myFragment, "myfragment");
  beginTransaction.commit();
  }
 });
 }
}

Fragment:

public class MyFragment extends Fragment {
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 View view = inflater.inflate(R.layout.my_fragment, container, false);
 TextView tv = (TextView) view.findViewById(R.id.text);
 //获取数据
 String text = getArguments().get("info") + "";
 tv.setText(text);
 return view;
 }
}

3.2 Activity向静态加载的Fragment传递数据

(1)在Fragment中创建作为容器的数据对象,并创建getter和setter;

(2)在Activity中获取FragmentManager;

(3)通过事务管理器的findFragmentById或findFragmentByTag方法,获得fragment对象;

(4)通过获得的fragment对象调用容器的setter方法进行传值。

范例:这里的布局与动态加载的布局唯一不同的就是将send按钮放在了Fragment里面,其它相同。

Fragment:

public class MyFragment extends Fragment {
 private Button btn;
 private String received;//作为容器的对象
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 View view = inflater.inflate(R.layout.my_fragment, container, false);
 TextView tv = (TextView) view.findViewById(R.id.text);
 tv.setText("这里是Fragment");
 btn = (Button) view.findViewById(R.id.send);
 btn.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  Toast.makeText(getActivity(), "成功接收\"" + getReceived() + "\"", Toast.LENGTH_SHORT).show();
  }
 });
 return view;
 }
 public String getReceived() {
 return received;
 }
 public void setReceived(String received) {
 this.received = received;
 }
}

Activity:

public class MainActivity extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 FragmentManager fragmentManager = getFragmentManager();
 MyFragment myFragment = (MyFragment) fragmentManager.findFragmentById(R.id.my_fragment);
 myFragment.setReceived("this is a test.");
 }
}

4. Fragment向Activity传递数据

(1)在Fragment中写一个回调接口;

(2)在activity中实现这个回调接口,实现的函数用于传值;

(3)重写Fragment中onAttach,在其中创建一个接口对象,得到传递过来的activity(我的理解是这个接口其实相当于传递过来的activity的一个父类,这一步是用到了多态的特性);

(4)用得到的接口对象进行传值。

Fragment:

public class MyFragment extends Fragment {
 private SendData sendData;
 @Override
 public void onAttach(Activity activity) {
 super.onAttach(activity);
 //获取实现的接口对象
 sendData = (SendData) activity;
 }
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 View view = inflater.inflate(R.layout.my_fragment, container, false);
 TextView tv = (TextView) view.findViewById(R.id.text);
 tv.setText("这里是Fragment");
 //通过接口对象传递数据
 sendData.sendMsg("this is a test.");
 return view;
 }
 //定义一个回调接口
 public interface SendData{
 void sendMsg(String str);
 }
}

Activity:

public class MainActivity extends Activity implements MyFragment.SendData{
 private Button btn;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 btn = (Button) findViewById(R.id.send);
 btn.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  MyFragment myFragment = new MyFragment();
  FragmentManager fragmentManager = getFragmentManager();
  FragmentTransaction beginTransaction = fragmentManager.beginTransaction();
  beginTransaction.add(R.id.layout, myFragment);
  beginTransaction.commit();
  }
 });
 }
 //实现SendData接口,接收数据
 @Override
 public void sendMsg(String str) {
 Toast.makeText(this, "成功接收\"" + str + "\"", Toast.LENGTH_SHORT).show();
 }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!


# android  # fragment通信  # fragment  # 懒加载  # 通信方式  # Android自定义ViewPagerIndicator实现炫酷导航栏指示器(ViewPager+F  # Android之Viewpager+Fragment实现懒加载示例  # Android 开发中fragment预加载问题  # Android开发技巧之Fragment的懒加载  # Android应用开发中Fragment的静态加载与动态加载实例  # Android中使用开源框架eventbus3.0实现fragment之间的通信交互  # Android Fragment与Activity之间的相互通信实例代码  # Android应用开发中Fragment与Activity间通信示例讲解  # Android应用开发中Fragment间通信的实现教程  # 加载  # 管理器  # 转换成  # 回调  # 自定义  # 只有一个  # 绑定  # 类中  # 放在  # 均为  # 数据通信  # 可以直接  # 重写  # 可直接  # 而对  # 若不  # 将该  # 用得  # 时将  # 值为 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: 网站图片在线制作软件,怎么在图片上做链接?  如何在 Pandas 中基于一列条件计算另一列的分组均值  什么是JavaScript解构赋值_解构赋值有哪些实用技巧  深圳防火门网站制作公司,深圳中天明防火门怎么编码?  javascript和jQuery中的AJAX技术详解【包含AJAX各种跨域技术】  JS中页面与页面之间超链接跳转中文乱码问题的解决办法  Laravel如何实现多级无限分类_Laravel递归模型关联与树状数据输出【方法】  canvas 画布在主流浏览器中的尺寸限制详细介绍  EditPlus 正则表达式 实战(3)  Laravel怎么实现观察者模式Observer_Laravel模型事件监听与解耦开发【指南】  网站页面设计需要考虑到这些问题  如何用已有域名快速搭建网站?  js实现获取鼠标当前的位置  英语简历制作免费网站推荐,如何将简历翻译成英文?  Laravel怎么实现模型属性的自动加密  如何在沈阳梯子盘古建站优化SEO排名与功能模块?  Laravel如何优化应用性能?(缓存和优化命令)  如何在腾讯云服务器上快速搭建个人网站?  Laravel API路由如何设计_Laravel构建RESTful API的路由最佳实践  如何在香港免费服务器上快速搭建网站?  如何彻底卸载建站之星软件?  如何用美橙互联一键搭建多站合一网站?  Laravel如何使用Vite进行前端资源打包?(配置示例)  Laravel如何实现登录错误次数限制_Laravel自带LoginThrottles限流配置【方法】  零基础网站服务器架设实战:轻量应用与域名解析配置指南  jquery插件bootstrapValidator表单验证详解  微信小程序 HTTPS报错整理常见问题及解决方案  三星、SK海力士获美批准:可向中国出口芯片制造设备  Laravel的.env文件有什么用_Laravel环境变量配置与管理详解  使用C语言编写圣诞表白程序  安克发布新款氮化镓充电宝:体积缩小 30%,支持 200W 输出  Laravel如何实现多表关联模型定义_Laravel多对多关系及中间表数据存取【方法】  如何安全更换建站之星模板并保留数据?  Laravel怎么导出Excel文件_Laravel Excel插件使用教程  如何在万网利用已有域名快速建站?  微信小程序 scroll-view组件实现列表页实例代码  Swift中switch语句区间和元组模式匹配  Laravel如何与Pusher实现实时通信?(WebSocket示例)  家族网站制作贴纸教程视频,用豆子做粘帖画怎么制作?  个人网站制作流程图片大全,个人网站如何注销?  佛山企业网站制作公司有哪些,沟通100网上服务官网?  Laravel如何操作JSON类型的数据库字段?(Eloquent示例)  详解免费开源的DotNet二维码操作组件ThoughtWorks.QRCode(.NET组件介绍之四)  Laravel如何实现多语言支持_Laravel本地化与国际化(i18n)配置教程  Laravel如何编写单元测试和功能测试?(PHPUnit示例)  头像制作网站在线观看,除了站酷,还有哪些比较好的设计网站?  Laravel Fortify是什么,和Jetstream有什么关系  小米17系列还有一款新机?主打6.9英寸大直屏和旗舰级影像  如何用AI一键生成爆款短视频文案?小红书AI文案写作指令【教程】  Laravel路由Route怎么设置_Laravel基础路由定义与参数传递规则【详解】