Fragment+FrameLayout实现Tab切换

本文介绍了如何使用Fragment和FrameLayout在Android应用中实现底部Tab切换的效果。通过创建多个Fragment作为页卡内容,并结合帧布局,展示了Tab切换的实现过程,同时讨论了直接替换Fragment和使用ViewPager两种方法的优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

底部切换效果已经很常见了,本文介绍其中的一种实现方法:FrameLayout+Fragment
本案例已上传至Github,你可以查看完整源码,也可以下载demo apk体验一下
实现效果如下:

这里写图片描述

Tab切换

Step1:创建Fragment
创建四个页卡所表示的Fragment以及其布局文件,图中每个页卡都是一个Fragment(碎片)

先创建第一个页卡的Fragment以及布局文件
fragment_tab1.xml

<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.zhuangfei.fragment.TabFragment1"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="第一个页卡" />

    <Button
        android:id="@+id/tab1_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="Fragment交互"/>

</LinearLayout>

TabFragment1.java


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

/**
 *第一个页卡
 * A simple {@link Fragment} subclass.
 */
public class TabFragment1 extends Fragment {
   

    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.fragment_tab1, container, false);

        Button button=view.findViewById(R.id.tab1_btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getContext(),"findViewById()时不要忘了前边的view."
                        ,Toast.LENGTH_SHORT).show();
            }
        });
        return view;
    }
}

以下copy3份,并简单的修改一下显示的文字
fragment_tab2.xml

<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.zhuangfei.fragment.TabFragment1">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="第二个页卡" />

&
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值