Open cisen opened 6 years ago
public class Fragment1 extends Fragment{
private static String ARG_PARAM = "param_key";
private String mParam;
private Activity mActivity;
public void onAttach(Context context) {
mActivity = (Activity) context;
mParam = getArguments().getString(ARG_PARAM); //获取参数
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_1, container, false);
TextView view = root.findViewById(R.id.text);
view.setText(mParam);
return root;
}
public static Fragment1 newInstance(String str) {
Fragment1 frag = new Fragment1();
Bundle bundle = new Bundle();
bundle.putString(ARG_PARAM, str);
fragment.setArguments(bundle); //设置参数
return fragment;
}
}
Fragment有很多可以复写的方法,其中最常用的就是onCreateView(),该方法返回Fragment的UI布局,需要注意的是inflate()的第三个参数是false,因为在Fragment内部实现中,会把该布局添加到container中,如果设为true,那么就会重复做两次添加,则会抛如下异常:
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
如果在创建Fragment时要传入参数,必须要通过setArguments(Bundle bundle)方式添加,而不建议通过为Fragment添加带参数的构造函数,因为通过setArguments()方式添加,在由于内存紧张导致Fragment被系统杀掉并恢复(re-instantiate)时能保留这些数据。官方建议如下:
It is strongly recommended that subclasses do not have other constructors with parameters, since these constructors will not be called when the fragment is re-instantiated.
我们可以在Fragment的onAttach()中通过getArguments()获得传进来的参数,并在之后使用这些参数。如果要获取Activity对象,不建议调用getActivity(),而是在onAttach()中将Context对象强转为Activity对象。
在Activity中添加Fragment的方式有两种:
虽然Fragment能在XML中添加,但是这只是一个语法糖而已,Fragment并不是一个View,而是和Activity同一层次的。 动态添加:
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
if (bundle == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, Fragment1.newInstance("hello world"), "f1")
//.addToBackStack("fname")
.commit();
}
这里需要注意几点:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1341)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1352)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
该异常出现的原因是:commit()在onSaveInstanceState()后调用。首先,onSaveInstanceState()在onPause()之后,onStop()之前调用。onRestoreInstanceState()在onStart()之后,onResume()之前。
因此避免出现该异常的方案有:
https://cloud.tencent.com/developer/article/1005538 Fragment是Android honeycomb 3.0新增的概念,Fragment名为碎片不过却和Activity十分相似。 Fragment是用来描述一些行为或一部分用户界面在一个Activity中, (1)你可以合并多个fragment在一个单独的activity中建立多个UI面板, (2)同时重用fragment在多个activity中。 你可以认为fragment作为一个activity中的一节模块 ,fragment有自己的生命周期,接收自己的输入事件,你可以添加或移除从运行中的activity。 从中可以看出:一个fragment必须总是嵌入在一个activity中,同时fragment的生命周期 受 activity而影响。当activity 暂停,那么所有在这个activity的fragments将被destroy释放。
Fragment核心的类有:
Fragment:Fragment的基类,任何创建的Fragment都需要继承该类。 FragmentManager:管理和维护Fragment。他是抽象类,具体的实现类是FragmentManagerImpl。 FragmentTransaction:对Fragment的添加、删除等操作都需要通过事务方式进行。他是抽象类,具体的实现类是BackStackRecord。 Nested Fragment(Fragment内部嵌套Fragment的能力)是Android 4.2提出的,support-fragment库可以兼容到1.6。通过getChildFragmentManager()能够获得管理子Fragment的FragmentManager,在子Fragment中可以通过getParentFragment()获得父Fragment。
activity and fragment
activity: fragment: activity && fragment
onAttach():Fragment和Activity相关联时调用。可以通过该方法获取Activity引用,还可以通过getArguments()获取参数。 onCreate():Fragment被创建时调用。 onCreateView():创建Fragment的布局。 onActivityCreated():当Activity完成onCreate()时调用。 onStart():当Fragment可见时调用。 onResume():当Fragment可见且可交互时调用。 onPause():当Fragment不可交互但可见时调用。 onStop():当Fragment不可见时调用。 onDestroyView():当Fragment的UI从视图结构中移除时调用。 onDestroy():销毁Fragment时调用。 onDetach():当Fragment和Activity解除关联时调用。
我们这里举个例子来理解Fragment生命周期方法。功能如下:共有两个Fragment:F1和F2,F1在初始化时就加入Activity,点击F1中的按钮调用replace替换为F2。
当F1在Activity的onCreate()中被添加时,日志如下:
BasicActivity: [onCreate] BEGIN BasicActivity: [onCreate] END BasicActivity: [onStart] BEGIN Fragment1: [onAttach] BEGIN Fragment1: [onAttach] END BasicActivity: [onAttachFragment] BEGIN BasicActivity: [onAttachFragment] END Fragment1: [onCreate] BEGIN Fragment1: [onCreate] END Fragment1: [onCreateView] Fragment1: [onViewCreated] BEGIN Fragment1: [onViewCreated] END Fragment1: [onActivityCreated] BEGIN Fragment1: [onActivityCreated] END Fragment1: [onStart] BEGIN Fragment1: [onStart] END BasicActivity: [onStart] END BasicActivity: [onPostCreate] BEGIN BasicActivity: [onPostCreate] END BasicActivity: [onResume] BEGIN BasicActivity: [onResume] END BasicActivity: [onPostResume] BEGIN Fragment1: [onResume] BEGIN Fragment1: [onResume] END BasicActivity: [onPostResume] END BasicActivity: [onAttachedToWindow] BEGIN BasicActivity: [onAttachedToWindow] END 可以看出:
Fragment的onAttach()->onCreate()->onCreateView()->onActivityCreated()->onStart()都是在Activity的onStart()中调用的。 Fragment的onResume()在Activity的onResume()之后调用。 接下去分两种情况,分别是不加addToBackStack()和加addToBackStack()。
1、当点击F1的按钮,调用replace()替换为F2,且不加addToBackStack()时,日志如下:
Fragment2: [onAttach] BEGIN Fragment2: [onAttach] END BasicActivity: [onAttachFragment] BEGIN BasicActivity: [onAttachFragment] END Fragment2: [onCreate] BEGIN Fragment2: [onCreate] END Fragment1: [onPause] BEGIN Fragment1: [onPause] END Fragment1: [onStop] BEGIN Fragment1: [onStop] END Fragment1: [onDestroyView] BEGIN Fragment1: [onDestroyView] END Fragment1: [onDestroy] BEGIN Fragment1: [onDestroy] END Fragment1: [onDetach] BEGIN Fragment1: [onDetach] END Fragment2: [onCreateView] Fragment2: [onViewCreated] BEGIN Fragment2: [onViewCreated] END Fragment2: [onActivityCreated] BEGIN Fragment2: [onActivityCreated] END Fragment2: [onStart] BEGIN Fragment2: [onStart] END Fragment2: [onResume] BEGIN Fragment2: [onResume] END 可以看到,F1最后调用了onDestroy()和onDetach()。
2、当点击F1的按钮,调用replace()替换为F2,且加addToBackStack()时,日志如下:
Fragment2: [onAttach] BEGIN Fragment2: [onAttach] END BasicActivity: [onAttachFragment] BEGIN BasicActivity: [onAttachFragment] END Fragment2: [onCreate] BEGIN Fragment2: [onCreate] END Fragment1: [onPause] BEGIN Fragment1: [onPause] END Fragment1: [onStop] BEGIN Fragment1: [onStop] END Fragment1: [onDestroyView] BEGIN Fragment1: [onDestroyView] END Fragment2: [onCreateView] Fragment2: [onViewCreated] BEGIN Fragment2: [onViewCreated] END Fragment2: [onActivityCreated] BEGIN Fragment2: [onActivityCreated] END Fragment2: [onStart] BEGIN Fragment2: [onStart] END Fragment2: [onResume] BEGIN Fragment2: [onResume] END 可以看到,F1被替换时,最后只调到了onDestroyView(),并没有调用onDestroy()和onDetach()。当用户点返回按钮回退事务时,F1会调onCreateView()->onStart()->onResume(),因此在Fragment事务中加不加addToBackStack()会影响Fragment的生命周期。
FragmentTransaction有一些基本方法,下面给出调用这些方法时,Fragment生命周期的变化:
add(): onAttach()->…->onResume()。 remove(): onPause()->…->onDetach()。 replace(): 相当于旧Fragment调用remove(),新Fragment调用add()。 show(): 不调用任何生命周期方法,调用该方法的前提是要显示的Fragment已经被添加到容器,只是纯粹把Fragment UI的setVisibility为true。 hide(): 不调用任何生命周期方法,调用该方法的前提是要显示的Fragment已经被添加到容器,只是纯粹把Fragment UI的setVisibility为false。 detach(): onPause()->onStop()->onDestroyView()。UI从布局中移除,但是仍然被FragmentManager管理。 attach(): onCreateView()->onStart()->onResume()。
通讯
Fragment向Activity传递数据
首先,在Fragment中定义接口,并让Activity实现该接口(具体实现省略):
在Fragment的onAttach()中,将参数Context强转为OnFragmentInteractionListener对象:
并在Fragment合适的地方调用mListener.onItemClick("hello")将”hello”从Fragment传递给Activity。
FABridge
由于通过接口的方式从Fragment向Activity进行数据传递比较麻烦,需要在Fragment中定义interface,并让Activity实现该interface,FABridge通过注解的形式免去了这些定义。
在build.gradle中添加依赖:
首先定义方法ID,这里为FAB_ITEM_CLICK,接着在Activity中定义接口:
最后,在Fragment中,通过以下形式调用”ID=FAB_ITEM_CLICK”的方法(该方法可能在Activity中,也可能在任何类中):
Activity向Fragment传递数据
Activity向Fragment传递数据比较简单,获取Fragment对象,并调用Fragment的方法即可,比如要将一个字符串传递给Fragment,则在Fragment中定义方法:
并在Activity中调用fragment.setString("hello")即可。
Fragment之间通信
由于Fragment之间是没有任何依赖关系的,因此如果要进行Fragment之间的通信,建议通过Activity作为中介,不要Fragment之间直接通信。
DialogFragment
DialogFragment是Android 3.0提出的,代替了Dialog,用于实现对话框。他的优点是:即使旋转屏幕,也能保留对话框状态。
如果要自定义对话框样式,只需要继承DialogFragment,并重写onCreateView(),该方法返回对话框UI。这里我们举个例子,实现进度条样式的圆角对话框。
进度条动画我们使用Lottie实现,Lottie动画从这里找到。使用非常方便,只需要下载JSON动画文件,然后在XML中写入:
然后通过下面代码显示对话框: