Android使用Fragment实现控制切换多个页面
<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li>1. 创建Fragment</li><ul class="second_class_ul"><li>1.1 创建Fragment类</li><li>1.2 创建Fragment布局文件</li></ul><li>2. 在Activity中管理Fragment</li><ul class="second_class_ul"><li>2.1 创建Activity布局文件</li><li>2.2 编写Activity代码</li></ul><li>3. 运行效果</li><ul class="second_class_ul"></ul><li>4.方法补充</li><ul class="second_class_ul"><li>方法一</li><li>方法二</li></ul></ul></div><p>在Android开发中,<code>Fragment</code> 是一个非常重要的组件,它允许开发者将复杂的界面拆分成更小、更易于管理的部分。通过使用 <code>Fragment</code>,我们可以在同一个Activity中实现多个页面的切换,从而提高应用的用户体验和灵活性。本文将详细介绍如何在Android中使用 <code>Fragment</code> 来控制多个页面的切换。</p><p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202512/2025120807580011.png" /></p>
<p class="maodian"></p><h2>1. 创建Fragment</h2>
<p>首先,我们需要创建几个 <code>Fragment</code> 类来代表不同的页面。每个 <code>Fragment</code> 类通常会有一个对应的布局文件。</p>
<p class="maodian"></p><h3>1.1 创建Fragment类</h3>
<p>假设我们要创建两个页面,分别为 <code>FirstFragment</code> 和 <code>SecondFragment</code>。</p>
<p>FirstFragment.java</p>
<div class="jb51code"><pre class="brush:java;">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;
public class FirstFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_first, container, false);
}
}</pre></div>
<p>SecondFragment.java</p>
<div class="jb51code"><pre class="brush:java;">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;
public class SecondFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_second, container, false);
}
}</pre></div>
<p class="maodian"></p><h3>1.2 创建Fragment布局文件</h3>
<p>接下来,我们需要为每个 <code>Fragment</code> 创建一个布局文件。</p>
<p>res/layout/fragment_first.xml</p>
<div class="jb51code"><pre class="brush:xml;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="这是第一个页面" />
</LinearLayout></pre></div>
<p>res/layout/fragment_second.xml</p>
<div class="jb51code"><pre class="brush:xml;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="这是第二个页面" />
</LinearLayout></pre></div>
<p class="maodian"></p><h2>2. 在Activity中管理Fragment</h2>
<p class="maodian"></p><h3>2.1 创建Activity布局文件</h3>
<p>我们需要在 <code>Activity</code> 的布局文件中定义一个 <code>FrameLayout</code> 作为 <code>Fragment</code> 的容器。</p>
<p>res/layout/activity_main.xml</p>
<div class="jb51code"><pre class="brush:xml;"><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="@+id/btn_switch_to_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="切换到第一个页面"
android:layout_alignParentBottom="true"
android:layout_marginBottom="16dp"
android:layout_centerHorizontal="true" />
<Button
android:id="@+id/btn_switch_to_second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="切换到第二个页面"
android:layout_above="@id/btn_switch_to_first"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp" />
</RelativeLayout></pre></div>
<p class="maodian"></p><h3>2.2 编写Activity代码</h3>
<p>在 <code>MainActivity</code> 中,我们需要处理按钮点击事件,并根据用户的操作切换 <code>Fragment</code>。</p>
<p>MainActivity.java</p>
<div class="jb51code"><pre class="brush:java;">import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
public class MainActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
// 默认显示第一个页面
switchFragment(new FirstFragment());
findViewById(R.id.btn_switch_to_first).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switchFragment(new FirstFragment());
}
});
findViewById(R.id.btn_switch_to_second).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switchFragment(new SecondFragment());
}
});
}
private void switchFragment(Fragment fragment) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.commit();
}
}</pre></div>
<p class="maodian"></p><h2>3. 运行效果</h2>
<p>完成上述步骤后,运行应用,你将看到两个按钮分别用于切换到不同的页面。点击“切换到第一个页面”按钮时,<code>FrameLayout</code> 将显示 <code>FirstFragment</code>;点击“切换到第二个页面”按钮时,<code>FrameLayout</code> 将显示 <code>SecondFragment</code>。</p>
<p class="maodian"></p><h2>4.方法补充</h2>
<p class="maodian"></p><h3>方法一</h3>
<p>下面是一个简单的示例,展示如何在一个活动中通过按钮点击来切换两个不同的 <code>Fragment</code>。</p>
<p><strong>1. 创建Fragment</strong></p>
<p>首先,我们需要创建两个 <code>Fragment</code> 类,每个类代表一个页面。</p>
<p><strong>FirstFragment.java:</strong></p>
<div class="jb51code"><pre class="brush:java;">import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class FirstFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_first, container, false);
}
}</pre></div>
<p><strong>SecondFragment.java:</strong></p>
<div class="jb51code"><pre class="brush:java;">import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class SecondFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_second, container, false);
}
}</pre></div>
<p><strong>2. 创建布局文件</strong></p>
<p>为每个 <code>Fragment</code> 创建一个布局文件。</p>
<p><strong>fragment_first.xml:</strong></p>
<div class="jb51code"><pre class="brush:xml;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is the First Fragment" />
</LinearLayout></pre></div>
<p><strong>fragment_second.xml:</strong></p>
<div class="jb51code"><pre class="brush:xml;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is the Second Fragment" />
</LinearLayout></pre></div>
<p><strong>3. 在主活动中管理Fragment</strong></p>
<p>接下来,在主活动中设置按钮,通过这些按钮来切换 <code>Fragment</code>。</p>
<p><strong>MainActivity.java:</strong></p>
<div class="jb51code"><pre class="brush:java;">import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 默认加载第一个Fragment
loadFragment(new FirstFragment());
}
public void onFirstFragmentClick(View view) {
loadFragment(new FirstFragment());
}
public void onSecondFragmentClick(View view) {
loadFragment(new SecondFragment());
}
private void loadFragment(Fragment fragment) {
// 创建一个新的事务
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
// 替换当前的Fragment
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(null); // 可选:将事务添加到回退栈
transaction.commit(); // 提交事务
}
}</pre></div>
<p><strong>activity_main.xml:</strong></p>
<div class="jb51code"><pre class="brush:xml;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_first"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="First Fragment"
android:onClick="onFirstFragmentClick" />
<Button
android:id="@+id/btn_second"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Second Fragment"
android:onClick="onSecondFragmentClick" />
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout></pre></div>
<p>在这个例子中,我们使用了 <code>FragmentManager</code> 来管理 <code>Fragment</code> 的生命周期,并使用 <code>FragmentTransaction</code> 来执行具体的替换操作。当用户点击按钮时,相应的 <code>Fragment</code> 将被加载到 <code>FrameLayout</code> 中,实现了页面的切换。在Android开发中,<code>Fragment</code> 是一种可以嵌入到 <code>Activity</code> 中的界面片段,它可以包含自己的布局和生命周期。使用 <code>Fragment</code> 可以创建更加灵活、可重用的UI组件,非常适合实现多页面切换的应用场景。</p>
<p class="maodian"></p><h3>方法二</h3>
<p>下面是一个简单的示例,介绍如何通过 <code>FragmentManager</code> 和 <code>FragmentTransaction</code> 来控制 <code>Fragment</code> 的切换:</p>
<p><strong>1. 创建Fragment</strong></p>
<p>首先,我们需要创建几个 <code>Fragment</code> 类。这里假设我们有两个 <code>Fragment</code>:<code>FirstFragment</code> 和 <code>SecondFragment</code>。</p>
<div class="jb51code"><pre class="brush:java;">// FirstFragment.java
public class FirstFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_first, container, false);
}
}
// SecondFragment.java
public class SecondFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_second, container, false);
}
}</pre></div>
<p><strong>2. 在Activity中设置Fragment</strong></p>
<p>接下来,在 <code>Activity</code> 中设置一个容器(例如一个 <code>FrameLayout</code>),用于放置 <code>Fragment</code>。</p>
<div class="jb51code"><pre class="brush:xml;"><!-- activity_main.xml -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="@+id/button_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First Fragment"
android:layout_alignParentBottom="true"
android:layout_marginBottom="50dp"
android:layout_centerHorizontal="true" />
<Button
android:id="@+id/button_second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second Fragment"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout></pre></div>
<p><strong>3. 控制Fragment的切换</strong></p>
<p>在 <code>MainActivity</code> 中,我们可以监听按钮点击事件,并根据点击的按钮来切换不同的 <code>Fragment</code>。</p>
<div class="jb51code"><pre class="brush:java;">// MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button buttonFirst;
private Button buttonSecond;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonFirst = findViewById(R.id.button_first);
buttonSecond = findViewById(R.id.button_second);
// 默认显示FirstFragment
loadFragment(new FirstFragment());
buttonFirst.setOnClickListener(v -> loadFragment(new FirstFragment()));
buttonSecond.setOnClickListener(v -> loadFragment(new SecondFragment()));
}
private void loadFragment(Fragment fragment) {
// 获取FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
// 开始事务
FragmentTransaction transaction = fragmentManager.beginTransaction();
// 替换当前Fragment
transaction.replace(R.id.fragment_container, fragment);
// 将事务添加到返回栈
transaction.addToBackStack(null);
// 提交事务
transaction.commit();
}
}</pre></div>
<p><strong>4. 处理返回键</strong></p>
<p>为了处理返回键,当用户从 <code>SecondFragment</code> 返回到 <code>FirstFragment</code> 时,可以在 <code>MainActivity</code> 中重写 <code>onBackPressed</code> 方法:</p>
<div class="jb51code"><pre class="brush:java;">@Override
public void onBackPressed() {
// 检查FragmentManager的回退栈是否有Fragment
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}</pre></div>
<p>这样,当用户点击返回键时,会先从回退栈中弹出最近的 <code>Fragment</code>,如果回退栈为空,则关闭 <code>Activity</code>。</p>
<p>以上就是使用 <code>Fragment</code> 切换多个页面的基本步骤。</p>
<p>到此这篇关于Android使用Fragment实现控制切换多个页面的文章就介绍到这了,更多相关Android切换页面内容请搜索琼殿技术社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持琼殿技术社区!</p>
<div class="art_xg">
<b>您可能感兴趣的文章:</b><ul><li>Android Flutter实现页面切换转场动画效果</li><li>Android ViewPager实现页面左右切换效果</li><li>Android实现带页面切换的锁屏功能</li><li>Android基于ViewPager实现类似微信页面切换效果</li><li>Android fragment实现多个页面切换效果</li><li>Android实现页面滑动切换动画</li><li>Android 实现无网络页面切换的示例代码</li></ul>
</div>
</div>
<!--endmain-->
頁:
[1]