2025-11-20 16:40:21,某些文章具有时效性,若有错误或已失效,请在下方留言。基本介绍
Fragment 代表应用程序 UI 可复用的部分。Fragment 定义和管理自己的布局,拥有自己的生命周期,并且可以处理自己的输入事件。Fragment 不能独自存在,它们必须由一个 Activity 或者另一个 Fragment 承载。
生命周期
Fragment 的生命周期,如下图所示
![图片[1]-Fragment-Stewed Noodles 资源](https://cdn.sa.net/2025/11/07/HVKrn2iYa6b8Mmq.webp)
onAttach()
在 Fragment 附加到 Activity 时调用,它接收 Activity 的引用,允许 Fragment 与 onCreate() 方法交互。
- 这个阶段,
Fragment被初始化。 - 在此方法中,执行一次性的设置任务,比如初始化变量和设置
Fragment。
onCreateView()
此方法会在宿主 Activity 的 onCreate 方法执行完成之后 被调用。在这一步中,Fragment 会通过 填充(inflate)布局文件 或 动态构建 UI 来创建其用户界面。
onStart()
Fragment 对用户可见,并即将变为活动状态。可以在此处开始动画或其它视觉效果。
onResume()
Fragment 变得可交互,任何需要响应用户交互的代码都应该放在这里,例如启动后台任务或者其它任务。
onPause()
当 Fragment 即将被其他 Fragment 或 Activity 覆盖时调用。
此方法被调用时,通常用于保存 Fragment 的状态,或停止任何正在进行的任务。
onStop()
Fragment 不再可见,因为它正在被替换、Activity 已暂停或者 Fragment 已被删除。您应该释放不再需要的资源或任务。
onDestroyView()
Fragment 的 UI 被破坏,在这一步中,您可以清理任何绑定到 UI 上的资源,例如视图和适配器。
onDestroy()
当 Fragment 即将被完全摧毁时调用。您应该在这里释放所有剩余的资源。
onDetach()
Fragment 从宿主 Activity 中分离。 此时,它不再具有对 Activity 的访问权限,您应该释放与之绑定的任何引用或资源。
示例代码
创建 Fragment
创建两个 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"
android:background="#019167"
tools:context=".FirstFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="48sp"
android:text="First Fragment" />
<Button
android:id="@+id/btn_frag1"
android:layout_marginTop="100dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Say Hello" />
</FrameLayout>
package com.stewednoodles.fragmentsapp;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FirstFragment extends Fragment {
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
Toast.makeText(context,
"onAttach() is Called",
Toast.LENGTH_SHORT).show();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(getActivity(),
"onCreate() is Called",
Toast.LENGTH_SHORT).show();
}
@Override
public void onResume() {
super.onResume();
Toast.makeText(getActivity(),
"onResume() is Called",
Toast.LENGTH_SHORT).show();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
Button button = view.findViewById(R.id.btn_frag1);
TextView textView = view.findViewById(R.id.text_view);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(
getActivity(),
"Welcome to The First Fragment",
Toast.LENGTH_SHORT
).show();
}
});
return view;
}
}
<?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"
android:background="#EEEBCD"
tools:context=".SecondFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="@+id/text_frag2"
android:textSize="48sp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Second Fragment" />
<Button
android:id="@+id/btn_frag2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Say Bye"
android:layout_marginTop="100dp"/>
</FrameLayout>
package com.stewednoodles.fragmentsapp;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class SecondFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, container, false);
TextView textView = view.findViewById(R.id.text_frag2);
Button button = view.findViewById(R.id.btn_frag2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Good Bye From Second Fragment", Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
页面布局
主页面 activity_main.xml 的布局代码
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#9FE2BF"
tools:context=".MainActivity">
<TextView
android:id="@+id/main_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="56dp"
android:text="Fragments App"
android:textColor="@color/black"
android:textSize="32sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="20dp"
android:text="Display Fragment 1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/main_text" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginEnd="16dp"
android:text="Display Fragment 2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/main_text" />
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="40dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn1" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java 文件内容
package com.stewednoodles.fragmentsapp;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
public class MainActivity extends AppCompatActivity {
Button btn1, btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadFragment(new FirstFragment());
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadFragment(new SecondFragment());
}
});
}
public void loadFragment(Fragment fragment) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frameLayout, fragment);
ft.commit();
}
}
运行效果
代码的运行效果,如下所示












暂无评论内容