敞开生长之旅!这是我参与「日新方案 12 月更文挑战」的第20天,点击查看活动概况
一、Fragment是什么?为什么要引进它?
是什么?
Fragment是Android3.0后引进的一个新的API,他出现的初衷是为了适应大屏幕的平板电脑, 当然现在他仍然是平板APP UI设计的宠儿,而且咱们一般手机开发也会参加这个Fragment, 咱们能够把他看成一个小型的Activity,又称Activity片段!想想,假如一个很大的界面,咱们 就一个布局,写起界面来会有多费事,而且假如组件多的话是办理起来也很费事!而运用Fragment 咱们能够把屏幕划分成几块,然后进行分组,进行一个模块化的办理!从而能够愈加便利的在 运转过程中动态地更新Activity的用户界面!别的Fragment并不能独自运用,他需求嵌套在Activity 中运用,尽管他拥有自己的生命周期,可是还是会遭到宿主Activity的生命周期的影响,比方Activity 被destory销毁了,他也会跟着销毁!
为什么引进它?
引用官方的一张图片,其实已经阐明问题了,便是为了更好的适配大屏,在大屏的时候,不需求去在一个activity内部经过复杂的布局和界面去完成,只需求去在一个activity内部,经过多个fragment来做界面布局完成即可,而且针对于多个fragment来说, 每个fragment有独自的生命周期,
二、运用办法
Demo样例,咱们在一个界面中,有上下两个fragment,如图所示:
1.动态加载
代码如下(示例): Step 1: activity布局文件,两个FrameLayout
task_test.xml
<?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:background="@color/white"
android:orientation="vertical">
<FrameLayout
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<FrameLayout
android:id="@+id/fragment2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
Step 2: Fragment创立,视图加载,数据赋值
BlankFragment .java
package com.itbird.fragment;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.itbird.R;
/**
* A simple {@link Fragment} subclass.
* Use the {@link BlankFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class BlankFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private String TAG = BlankFragment.class.getSimpleName();
public BlankFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment BlankFragment.
*/
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public void onStart() {
Log.d(TAG, "onStart");
super.onStart();
}
@Override
public void onStop() {
Log.d(TAG, "onStop");
super.onStop();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
Log.d(TAG, "onViewCreated");
super.onViewCreated(view, savedInstanceState);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
Log.d(TAG, "onActivityCreated");
super.onActivityCreated(savedInstanceState);
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
}
@Override
public void onDestroyView() {
Log.d(TAG, "onDestroyView");
super.onDestroyView();
}
@Override
public void onDetach() {
Log.d(TAG, "onDetach");
super.onDetach();
}
@Override
public void onAttach(@NonNull Context context) {
Log.d(TAG, "onAttach");
super.onAttach(context);
}
@Override
public void onHiddenChanged(boolean hidden) {
Log.d(TAG, "onHiddenChanged");
super.onHiddenChanged(hidden);
}
@Override
public void onResume() {
Log.d(TAG, "onResume");
super.onResume();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.d(TAG, "onCreateView");
View view = inflater.inflate(R.layout.fragment_blank, container, false);
textView = view.findViewById(R.id.textview);
textView.setText(mParam1 + " " + mParam2);
return view;
}
TextView textView;
}
Step 3: Activity在onCreate( )办法中调用setContentView()之后调用FragmentTransaction 进行业务提交
FragmentTestActivity.java
package com.itbird.fragment;
import android.os.Bundle;
import android.util.Log;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;
import com.itbird.R;
public class FragmentTestActivity extends FragmentActivity {
private static final String TAG = FragmentTestActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task_test);
Log.e(TAG, TAG + " onCreate");
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment1, BlankFragment.newInstance("name1", "age1"), "top");
transaction.add(R.id.fragment2, BlankFragment.newInstance("name2", "age2"), "bootom");
transaction.commit();
}
@Override
public void onStart() {
Log.d(TAG, "onStart");
super.onStart();
}
@Override
public void onStop() {
Log.d(TAG, "onStop");
super.onStop();
}
@Override
public void onResume() {
Log.d(TAG, "onResume");
super.onResume();
}
@Override
protected void onPause() {
Log.d(TAG, "onPause");
super.onPause();
}
@Override
protected void onDestroy() {
Log.e(TAG, TAG + " onDestroy");
super.onDestroy();
}
}
2.静态加载
在xml中声明两个fragment,指定为详细的fragment
Step 1:定义Fragment的布局,便是fragment显现内容的
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".fragment.BlankFragment">
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />
</FrameLayout>
Step 2:自定义一个Fragment类,需求继承Fragment或许他的子类,重写onCreateView()办法 在该办法中调用:inflater.inflate()办法加载Fragment的布局文件,接着返回加载的view目标
BlankFragment.java
package com.itbird.fragment;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.itbird.R;
/**
* A simple {@link Fragment} subclass.
* Use the {@link BlankFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class BlankFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private String TAG = BlankFragment.class.getSimpleName();
public BlankFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment BlankFragment.
*/
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public void onStart() {
Log.d(TAG, "onStart");
super.onStart();
}
@Override
public void onStop() {
Log.d(TAG, "onStop");
super.onStop();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
Log.d(TAG, "onViewCreated");
super.onViewCreated(view, savedInstanceState);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
Log.d(TAG, "onActivityCreated");
super.onActivityCreated(savedInstanceState);
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
}
@Override
public void onDestroyView() {
Log.d(TAG, "onDestroyView");
super.onDestroyView();
}
@Override
public void onDetach() {
Log.d(TAG, "onDetach");
super.onDetach();
}
@Override
public void onAttach(@NonNull Context context) {
Log.d(TAG, "onAttach");
super.onAttach(context);
}
@Override
public void onHiddenChanged(boolean hidden) {
Log.d(TAG, "onHiddenChanged");
super.onHiddenChanged(hidden);
}
@Override
public void onResume() {
Log.d(TAG, "onResume");
super.onResume();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.d(TAG, "onCreateView");
View view = inflater.inflate(R.layout.fragment_blank, container, false);
textView = view.findViewById(R.id.textview);
textView.setText(mParam1 + " " + mParam2);
return view;
}
TextView textView;
}
Step 3:在需求加载Fragment的Activity对应的布局文件中添加fragment的标签, 记住,name特点是全限定类名哦,便是要包括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"
android:background="@color/white"
android:orientation="vertical">
<androidx.fragment.app.FragmentContainerView
android:name="com.itbird.fragment.BlankFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<androidx.fragment.app.FragmentContainerView
android:name="com.itbird.fragment.BlankFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
Step 4: Activity在onCreate( )办法中调用setContentView()加载布局文件即可!
package com.itbird.fragment;
import android.os.Bundle;
import android.util.Log;
import com.itbird.R;
public class FragmentTestActivity extends FragmentActivity {
private static final String TAG = FragmentTestActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task_test);
Log.e(TAG, TAG + " onCreate");
}
}
三、生命周期
几种状况下,fragment生命周期: ①Activity加载Fragment的时候,依次调用下面的办法: onAttach -> onCreate -> onCreateView -> onActivityCreated -> onStart ->onResume ②当咱们弄出一个悬浮的对话框风格的Activity,或许其他,便是让Fragment地点的Activity可见,但不取得焦点 onPause ③当对话框封闭,Activity又取得了焦点: onResume ④当咱们替换Fragment,并调用addToBackStack()将他添加到Back栈中 onPause -> onStop -> onDestoryView !!留意,此刻的Fragment还没有被销毁哦!!! ⑤当咱们按下键盘的回退键,Fragment会再次显现出来: onCreateView -> onActivityCreated -> onStart -> onResume ⑥假如咱们替换后,在业务commit之前没有调用addToBackStack()办法将 Fragment添加到back栈中的话;又或许退出了Activity的话,那么Fragment将会被完全结束, Fragment会进入销毁状态 onPause -> onStop -> onDestoryView -> onDestory -> onDetach
四、首要办法
针对在一个Activity中的某个Layout中切换Fragment,,无非两种办法:
1)replace
咱们自己看一下办法注释
/**
* Replace an existing fragment that was added to a container. This is
* essentially the same as calling {@link #remove(Fragment)} for all
* currently added fragments that were added with the same containerViewId
* and then {@link #add(int, Fragment, String)} with the same arguments
* given here.
*
* @param containerViewId Identifier of the container whose fragment(s) are
* to be replaced.
* @param fragment The new fragment to place in the container.
* @param tag Optional tag name for the fragment, to later retrieve the
* fragment with {@link FragmentManager#findFragmentByTag(String)
* FragmentManager.findFragmentByTag(String)}.
*
* @return Returns the same FragmentTransaction instance.
*/
@NonNull
public FragmentTransaction replace(@IdRes int containerViewId, @NonNull Fragment fragment,
@Nullable String tag) {
if (containerViewId == 0) {
throw new IllegalArgumentException("Must use non-zero containerViewId");
}
doAddOp(containerViewId, fragment, tag, OP_REPLACE);
return this;
}
源码办法注释里边说的很理解,这个办法会移除一切的fragment,然后添加当前的fragment。 这时分为两种状况,一种是fragment已有而且在前台展现,一种是未有或许在后台,针对于前者,此刻replace,生命周期不会发生变化,针对后者,生命周期会从头走
2022-03-18 15:51:53.408 1141-1141/com.itbird D/BlankFragment1: onAttach
2022-03-18 15:51:53.408 1141-1141/com.itbird D/BlankFragment1: onCreate
2022-03-18 15:51:53.411 1141-1141/com.itbird D/BlankFragment1: onCreateView
2022-03-18 15:51:53.414 1141-1141/com.itbird D/BlankFragment1: onViewCreated
2022-03-18 15:51:53.414 1141-1141/com.itbird D/BlankFragment1: onActivityCreated
2022-03-18 15:51:53.416 1141-1141/com.itbird D/BlankFragment1: onStart
2022-03-18 15:51:53.418 1141-1141/com.itbird D/BlankFragment2: onDestroyView
2022-03-18 15:51:53.419 1141-1141/com.itbird D/BlankFragment2: onDestroy
2022-03-18 15:51:53.419 1141-1141/com.itbird D/BlankFragment2: onDetach
2022-03-18 15:51:53.420 1141-1141/com.itbird D/BlankFragment1: onResume
2)add+hide+show
分为两种状况,一种fragment已存在,一种未存在,针对于前者,生命周期无变化,可是会回调onHiddenChanged办法,针对于后者,生命周期会创立一次。
2022-03-18 16:02:30.520 2410-2410/com.itbird D/FragmentTestActivity: fragment1 = BlankFragment1{21ae25c} (4a8180fe-e646-4cca-89a5-0f617e61eb45)
2022-03-18 16:02:30.546 2410-2410/com.itbird D/BlankFragment1: onAttach
2022-03-18 16:02:30.547 2410-2410/com.itbird D/BlankFragment1: onCreate
2022-03-18 16:02:30.548 2410-2410/com.itbird D/BlankFragment1: onCreateView
2022-03-18 16:02:30.580 2410-2410/com.itbird D/BlankFragment1: onViewCreated
2022-03-18 16:02:30.582 2410-2410/com.itbird D/BlankFragment1: onActivityCreated
2022-03-18 16:02:30.585 2410-2410/com.itbird D/BlankFragment1: onStart
2022-03-18 16:02:30.590 2410-2410/com.itbird D/BlankFragment1: onResume
2022-03-18 16:02:35.302 2410-2410/com.itbird D/FragmentTestActivity: fragment1 = BlankFragment1{21ae25c} (4a8180fe-e646-4cca-89a5-0f617e61eb45 id=0x7f0801b7)
2022-03-18 16:02:35.308 2410-2410/com.itbird D/BlankFragment1: onHiddenChanged
2022-03-18 16:02:35.312 2410-2410/com.itbird D/BlankFragment1: onHiddenChanged
2022-03-18 16:02:37.212 2410-2410/com.itbird D/FragmentTestActivity: fragment1 = BlankFragment1{21ae25c} (4a8180fe-e646-4cca-89a5-0f617e61eb45 id=0x7f0801b7)
2022-03-18 16:02:37.219 2410-2410/com.itbird D/BlankFragment1: onHiddenChanged
2022-03-18 16:02:37.220 2410-2410/com.itbird D/BlankFragment1: onHiddenChanged
2022-03-18 16:02:39.500 2410-2410/com.itbird D/FragmentTestActivity: fragment1 = BlankFragment1{21ae25c} (4a8180fe-e646-4cca-89a5-0f617e61eb45 id=0x7f0801b7)
2022-03-18 16:02:39.509 2410-2410/com.itbird D/BlankFragment1: onHiddenChanged
2022-03-18 16:02:39.510 2410-2410/com.itbird D/BlankFragment1: onHiddenChanged
2022-03-18 16:02:41.125 2410-2410/com.itbird D/FragmentTestActivity: fragment1 = BlankFragment1{21ae25c} (4a8180fe-e646-4cca-89a5-0f617e61eb45 id=0x7f0801b7)
2022-03-18 16:02:41.126 2410-2410/com.itbird D/BlankFragment1: onHiddenChanged
2022-03-18 16:02:41.130 2410-2410/com.itbird D/BlankFragment1: onHiddenChanged
2022-03-18 16:02:50.987 2410-2410/com.itbird D/FragmentTestActivity: fragment2 = BlankFragment2{8536d4a} (05586a4a-4abd-4d28-8ad4-2630c17a50c5)
2022-03-18 16:02:50.999 2410-2410/com.itbird D/BlankFragment1: onHiddenChanged
2022-03-18 16:02:51.000 2410-2410/com.itbird D/BlankFragment2: onAttach
2022-03-18 16:02:51.000 2410-2410/com.itbird D/BlankFragment2: onCreate
2022-03-18 16:02:51.002 2410-2410/com.itbird D/BlankFragment2: onCreateView
2022-03-18 16:02:51.004 2410-2410/com.itbird D/BlankFragment2: onViewCreated
2022-03-18 16:02:51.005 2410-2410/com.itbird D/BlankFragment2: onActivityCreated
2022-03-18 16:02:51.005 2410-2410/com.itbird D/BlankFragment2: onStart
2022-03-18 16:02:51.007 2410-2410/com.itbird D/BlankFragment2: onResume
2022-03-18 16:02:55.315 2410-2410/com.itbird D/FragmentTestActivity: fragment2 = BlankFragment2{8536d4a} (05586a4a-4abd-4d28-8ad4-2630c17a50c5 id=0x7f0801b7)
2022-03-18 16:02:55.316 2410-2410/com.itbird D/BlankFragment2: onHiddenChanged
2022-03-18 16:02:55.317 2410-2410/com.itbird D/BlankFragment2: onHiddenChanged
2022-03-18 16:02:57.005 2410-2410/com.itbird D/FragmentTestActivity: fragment1 = BlankFragment1{21ae25c} (4a8180fe-e646-4cca-89a5-0f617e61eb45 id=0x7f0801b7)
2022-03-18 16:02:57.024 2410-2410/com.itbird D/BlankFragment2: onHiddenChanged
2022-03-18 16:02:57.025 2410-2410/com.itbird D/BlankFragment1: onHiddenChanged
总结
1.Fragment是Google官方引进的一个为了适配大屏、多页面的一个组件。您能够理解为它便是一个类罢了,只不过里边包括了View,而且与activity的生命周期进行了相关。 2.动态加载与静态加载相对来说,主张运用动态加载,静态加载固定在了xml文件中,永久不变。 3.replace的fragment假如不在前台,会履行一切生命周期,反之不会履行任何生命周期办法;hide+show生命周期并不会发生变化,可是会回调onHiddenChanged办法,在实际开发中,主张add之后,运用hide+show来操作fragment,一方面减少资源的重复加载和创立,别的一方面提高用户体验感。 4.fragment的生命周期大体上和activity一致,可是前期和后期多了一些东西,由于fragment内部有view,那么这个view需求进行创立、然后添加到activity内部,所以相应的在onCreate与onStart之间就多了几个办法-onCreateView、onViewCreated。相同的道理,fragment的view与activity解绑,也相应的在onStop与onDestory之间多个办法-onDestroyView。onAttach与onDetach能够理解为视图与activity产生相关和接触相关,是最开端和最终的过程。
Demo地址