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

一、加载方式

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(); } }

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

时间: 2024-07-31 12:35:09

Android中Fragment的加载方式与数据通信详解的相关文章

Android Webview添加网页加载进度条实例详解

推荐阅读:Android WebView线性进度条实例详解 最近在android项目中使用webview嵌套了一个抽奖活动网页,活动上线,运行良好(改了N次需求和突发bug),还好这种模式的活动,只需要修改网页,不需要重新打包发布市场,这也是这种模式开发的优势之一.后来据产品哥反馈说加载网页无进度提示,好吧,这个当时真没考虑这么多,这个要加加..想当然以为轻松搞定之....其实还是比轻松要复杂点... 1.首先自定义一个WebView控件 /** * 带进度条的Webivew * @author

Android 开发中fragment预加载问题

我们在做应用开发的时候,一个Activity里面可能会以viewpager(或其他容器)与多个Fragment来组合使用,而如果每个fragment都需要去加载数据,或从本地加载,或从网络加载,那么在这个activity刚创建的时候就变成需要初始化大量资源.这样的结果,我们当然不会满意.那么,能不能做到当切换到这个fragment的时候,它才去初始化呢? 答案就在Fragment里的setUserVisibleHint这个方法里.请看关于Fragment里这个方法的API文档(国内镜像地址:ht

android 让fragment重新加载

问题描述 android 让fragment重新加载 我用的是add切换方式,后退是用后退栈,每次不调用oncreateview方法,我现在 想要每次后退都是加载oncreateview方法,怎么实现呢,我知道用替换来做可以重新加载. 解决方案 Android 关于fragment切换重新加载的解决分享给大家Android之取消ViewPage+Fragment的预加载Android之取消ViewPage+Fragment的预加载 解决方案二: 你这种用的是原来的fragment,所以不会调用o

Android中利用动态加载实现手机淘宝的节日特效_Android

相信去年圣诞节打开过手机淘宝的童鞋都会对当时的特效记忆犹新吧:全屏飘雪,旁边还有个小雪人来控制八音盒背景音乐的播放,让人有种身临其境的感觉,甚至忍不住想狠狠购物了呢(误),大概就是下面这个样子滴: 嗯,确实很炫,那么我们一步步去分析是如何实现的: 一.实现下雪的 View 首先,最上面一层的全屏雪花极有可能是一个顶层的View,而这个View是通过动态加载去控制显示的(不更新淘宝也能看到这个效果).那么我们先得实现雪花效果的 View,人生苦短,拿来就用.打开 gank.io,搜索"雪花&quo

Android中利用动态加载实现手机淘宝的节日特效

相信去年圣诞节打开过手机淘宝的童鞋都会对当时的特效记忆犹新吧:全屏飘雪,旁边还有个小雪人来控制八音盒背景音乐的播放,让人有种身临其境的感觉,甚至忍不住想狠狠购物了呢(误),大概就是下面这个样子滴: 嗯,确实很炫,那么我们一步步去分析是如何实现的: 一.实现下雪的 View 首先,最上面一层的全屏雪花极有可能是一个顶层的View,而这个View是通过动态加载去控制显示的(不更新淘宝也能看到这个效果).那么我们先得实现雪花效果的 View,人生苦短,拿来就用.打开 gank.io,搜索"雪花&quo

隐藏-Android中的webview加载完成前后如何用一个图片来进行遮挡加载延迟的闪烁

问题描述 Android中的webview加载完成前后如何用一个图片来进行遮挡加载延迟的闪烁 用webview加载一个链接,但因为网速或者网页内容等问题,出现延迟,但是如果直接打开APP就开始加载的话,如果用户没有网络的情况下打开APP就什么都看不到了.所以想整个LOGO之类的全屏图片,等加载完成了之后再隐藏这个图片.该怎么实现,着急,在线等..... 解决方案 做个全屏的layout,等webview加载完就隐藏掉,在onPageFinished里处理 加载前可以先判断网络是不连通,不通就显示

在android中使用webview加载完一个网页后,如何知道一共加载了多少资源?

问题描述 在android中使用webview加载完一个网页后,如何知道一共加载了多少资源? RT,现在有一个需求要知道用webview加载完任意一个网页后一共有多少个资源,现在问题是不知道什么时候网页完全加载完,因为当webclient回调onPageFinished()之后,还是会继续回调onLoadResource()来加载资源,求给个思路 解决方案 用抓包工具(wireshark)即可查看 解决方案二: 可以在底层抓包实现哦... 解决方案三: 多少资源? 包括多少个图片js 吗 ? 分

android中使用jdbc, 加载驱动时总捕获到异常

问题描述 android中使用jdbc, 加载驱动时总捕获到异常 lacat详细信息 jar包我已经add libraries了,问题还是存在 解决方案 最好不要在安卓端用jdbc吧,服务器写php吧,jdbc不推荐的,效率和安全性都不高 解决方案二: 我就问你手机里哪有mysql数据库 解决方案三: e1.printSackTrace(),看这句话的具体错误信息 解决方案四: 你这个出错什么错误了,详细信息打印出来? 你是要连接远程的mysql 吗? 解决方案五: 并没有看到错误是什么,,

android最新的动态加载 方式secureDexClassLoader

问题描述 android最新的动态加载 方式secureDexClassLoader android最新的动态加载 方式secureDexClassLoader,谁能详细讲解一下呢,没找到 中文资料,英文有些细节还有点模糊! 解决方案 难道就没有人会么????????????