Android之Fragment实现界面切换学习笔记

本文是关于Android使用Fragment实现界面切换的学习笔记,通过创建并管理多个Fragment,展示了一个包含四个基本页面的简单Demo。文中提供了关键代码示例,并提到了如何去除默认ActionBar,替换为自定义顶部栏。同时预告了后续将实现类似微信的点击和滑动切换页面的功能。

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

Android之Fragment实现界面切换学习笔记

  今天来实现一个简单的界面切换功能,关于页面的切换相信大家都非常熟悉,比如微信、QQ、支付宝等这些常用软件都会有界面切换功能,根据软件的要求不同,我们所设计的页面切换个数也会不同,今天我就写一个四个基本页面切换的小Demo,具体的代码功能都会在注释上写上。
  
  PS:如果想和是我一样的效果,记得先把系统默认的ActionBar去掉,在头部添加我们自定义的top_bar,我们只需要在AndroidManifest.xml中修改一下android:theme="@style/AppTheme"为以下代码
 android:theme="@style/Theme.AppCompat.Light.NoActionBar"
  
  
  下面先看看界面效果吧:

这里写图片描述

BaseFragment.java

/**
 * 公用的界面,考虑到通用性,就先写一个简单的BaseFragment吧
 * 所有子类界面只需要设置简单的界面内容即可
 */
public abstract class BaseFragment extends Fragment {

    //公用内容设置
    private TextView mBaseTvTitle;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_base, container, false);
        mBaseTvTitle = ((TextView) view.findViewById(R.id.BaseTvTitle));
        setTitle(mBaseTvTitle);
        return view;
    }

    /**
     * 让子类去实现对应的内容
     * @param tvTitle
     */
    protected abstract void setTitle(TextView tvTitle);
}

FLFragment .java

/**
 * 分类Fragment
 */
public class FLFragment extends BaseFragment {
    /**
     * 设置对应的内容即可
     * @param tvTitle
     */
    @Override
    protected void setTitle(TextView tvTitle) {
        tvTitle.setText("分类界面");
        tvTitle.setTextSize(30);
        tvTitle.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
    }
}

RMFragment .java

/**
 * 热门Fragment
 */
public class RMFragment extends BaseFragment {

    @Override
    protected void setTitle(TextView tvTitle) {
        tvTitle.setText("热门界面");
        tvTitle.setTextSize(30);
        tvTitle.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
    }

}

Fragment.java

/**
 *  指南Fragment
 */
public class ZNFragment extends BaseFragment {


    @Override
    protected void setTitle(TextView tvTitle) {
        tvTitle.setText("指南界面");
        tvTitle.setTextSize(30);
        tvTitle.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
    }

}

WDFragment .java

/**
 * 我的Fragment
 */
public class WDFragment extends BaseFragment {


    @Override
    protected void setTitle(TextView tvTitle) {
        tvTitle.setText("我的界面");
        tvTitle.setTextSize(30);
        tvTitle.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
    }

}

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    //分类页面常量
    private final int FL = 1;
    //指南页面常量
    private final int ZN = 2;
    //热门页面常量
    private final int RM = 3;
    //我的页面常量
    private final int WD = 4;

    //指南页面布局控件
    private LinearLayout mLinZN;
    //分类页面布局控件
    private LinearLayout mLinFL;
    //热门页面布局控件
    private LinearLayout mLinRM;
    //我的页面布局控件
    private LinearLayout mLinWD;

    //分类Fragment
    private Fragment mFLFragment;
    //指南Fragment
    private Fragment mZNFragment;
    //我的Fragment
    private Fragment mWDFragment;
    //热门Fragment
    private Fragment mRMFragment;

    //热门ImageButton控件
    private ImageButton mRMIBtn;
    //指南ImageButton控件
    private ImageButton mZNIBtn;
    //分类ImageButton控件
    private ImageButton mFLIBtn;
    //我的ImageButton控件
    private ImageButton mWDIBtn;

    //热门文字控件
    private TextView mRMTv;
    //指南文字控件
    private TextView mZNTv;
    //分类文字控件
    private TextView mFLTv;
    //我的文字控件
    private TextView mWDTv;
    private FragmentManager manager;
    private FragmentTransaction transaction;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        event();
    }

    /**
     * 初始化所有控件
     */
    private void initView() {
        mLinZN = (LinearLayout) findViewById(R.id.mLinZN);
        mLinFL = (LinearLayout) findViewById(R.id.mLinFenLei);
        mLinRM = (LinearLayout) findViewById(R.id.mLinReMen);
        mLinWD = (LinearLayout) findViewById(R.id.mLinUser);
        mRMIBtn = (ImageButton) findViewById(R.id.mBtnRM);
        mZNIBtn = (ImageButton) findViewById(R.id.mBtnZN);
        mFLIBtn = (ImageButton) findViewById(R.id.mBtnFL);
        mWDIBtn = (ImageButton) findViewById(R.id.mBtnWD);
        mRMTv = (TextView) findViewById(R.id.mTvReMen);
        mZNTv = (TextView) findViewById(R.id.mTvZhiNan);
        mFLTv = (TextView) findViewById(R.id.mTvFenLei);
        mWDTv = (TextView) findViewById(R.id.mTvUser);
        manager = getSupportFragmentManager();
    }

    /**
     * 初始化事件
     */
    private void event() {
        mLinFL.setOnClickListener(this);
        mLinRM.setOnClickListener(this);
        mLinWD.setOnClickListener(this);
        mLinZN.setOnClickListener(this);
    }

    /**
     * 初始化所有控件状态为原始状态
     */
    private void initColor() {
        mRMTv.setTextColor(getResources().getColor(R.color.normal));
        mZNTv.setTextColor(getResources().getColor(R.color.normal));
        mFLTv.setTextColor(getResources().getColor(R.color.normal));
        mWDTv.setTextColor(getResources().getColor(R.color.normal));
        mRMIBtn.setBackgroundResource(R.mipmap.remen_normal);
        mZNIBtn.setBackgroundResource(R.mipmap.zhinan_normal);
        mFLIBtn.setBackgroundResource(R.mipmap.fenlei_normal);
        mWDIBtn.setBackgroundResource(R.mipmap.user_normal);
    }

    /**
     * 隐藏所有已经显示了Fragment
     * @param transaction
     */
    private void hint(FragmentTransaction transaction) {
        if(mZNFragment != null){
            transaction.hide(mZNFragment);
        }
        if(mFLFragment != null){
            transaction.hide(mFLFragment);
        }
        if(mWDFragment != null){
            transaction.hide(mWDFragment);
        }
        if(mRMFragment != null){
            transaction.hide(mRMFragment);
        }
    }


    @Override
    public void onClick(View view) {
        initColor();
        switch (view.getId()){
            case R.id.mLinFenLei:
                //添加分类布局的Fragment
                addFragment(FL);
                break;
            case R.id.mLinReMen:
                //添加热门布局的Fragment
                addFragment(RM);
                break;
            case R.id.mLinUser:
                //添加我的布局的Fragment
                addFragment(WD);
                break;
            case R.id.mLinZN:
                //添加指南布局的Fragment
                addFragment(ZN);
                break;
        }
    }

    /**
     * 添加对应的布局,根据传来的ID进行添加
     * @param index
     */
    private void addFragment(int index){
        //获取事物
        transaction = manager.beginTransaction();
        //每次先隐藏所有的Fragment,然后加载当前要显示的Fragment
        hint(transaction);
        switch (index){
            case FL:
                //设置当前的文字和ImageButton为橙色
                mFLTv.setTextColor(getResources().getColor(R.color.pressed));
                mFLIBtn.setBackgroundResource(R.mipmap.fenlei_pressed);
                //初次加载Fragment先判断是否为空
                if(mFLFragment == null){
                    mFLFragment = new FLFragment();
                    //第一次添加到Fragment中
                    transaction.add(R.id.mFrame,mFLFragment);
                }else{
                    //以后的每一次只需要显示即可
                    transaction.show(mFLFragment);
                }
                break;
            case RM:
                mRMTv.setTextColor(getResources().getColor(R.color.pressed));
                mRMIBtn.setBackgroundResource(R.mipmap.remen_pressed);
                if(mRMFragment == null){
                    mRMFragment = new RMFragment();
                    transaction.add(R.id.mFrame,mRMFragment);
                }else{
                    transaction.show(mRMFragment);
                }
                break;
            case WD:
                mWDTv.setTextColor(getResources().getColor(R.color.pressed));
                mWDIBtn.setBackgroundResource(R.mipmap.user_pressed);
                if(mWDFragment == null){
                    mWDFragment = new WDFragment();
                    transaction.add(R.id.mFrame,mWDFragment);
                }else{
                    transaction.show(mWDFragment);
                }
                break;
            case ZN:
                mZNTv.setTextColor(getResources().getColor(R.color.pressed));
                mZNIBtn.setBackgroundResource(R.mipmap.zhinan_pressed);
                if(mZNFragment == null){
                    mZNFragment = new ZNFragment();
                    transaction.add(R.id.mFrame,mZNFragment);
                }else{
                    transaction.show(mZNFragment);
                }
                break;
        }
        //最后记得提交
        transaction.commit();
    }
}

fragment_base.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/BaseTvTitle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>

activity_main.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"
    >
    <include layout="@layout/top_bar" android:id="@+id/mTopBar"/>
    <FrameLayout
        android:id="@+id/mFrame"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:layout_below="@+id/mTopBar"
        >
    </FrameLayout>

    <include layout="@layout/foot_bar" android:id="@+id/mFootBar"
        />
</LinearLayout>

foot_bar.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="65dp"
    android:orientation="vertical">

    <!--线条灰色线条-->
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@drawable/line" />

    <LinearLayout
        android:id="@+id/mFootBar"
        android:layout_width="match_parent"
        android:layout_height="65dp"
        android:layout_alignParentBottom="true"
        android:gravity="center"
        android:orientation="horizontal">


        <LinearLayout
            android:id="@+id/mLinZN"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <ImageButton
                android:id="@+id/mBtnZN"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:background="@mipmap/zhinan_pressed"
                android:button="@null"
                android:clickable="false" />

            <TextView
                android:id="@+id/mTvZhiNan"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:text="指南"
                android:textColor="#eb4f38" />

        </LinearLayout>


        <LinearLayout
            android:id="@+id/mLinReMen"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <ImageButton
                android:id="@+id/mBtnRM"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:background="@mipmap/remen_normal"
                android:clickable="false" />

            <TextView
                android:id="@+id/mTvReMen"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:text="热门" />

        </LinearLayout>


        <LinearLayout
            android:id="@+id/mLinFenLei"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <ImageButton
                android:id="@+id/mBtnFL"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:background="@mipmap/fenlei_normal"
                android:clickable="false" />

            <TextView
                android:id="@+id/mTvFenLei"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:text="分类" />

        </LinearLayout>


        <LinearLayout
            android:id="@+id/mLinUser"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical">

            <ImageButton
                android:id="@+id/mBtnWD"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:background="@mipmap/user_normal"
                android:clickable="false" />

            <TextView
                android:id="@+id/mTvUser"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:text="我的" />

        </LinearLayout>

    </LinearLayout>
</LinearLayout>

top_bar.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="50dp"
    android:orientation="horizontal"
    android:background="#FF2D47"
    >
    <ImageButton
        android:layout_width="28dp"
        android:layout_height="28dp"
        android:background="@mipmap/shape1"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp"
        />
    <TextView

        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="礼物说"
        android:textSize="25sp"
        android:textColor="#ffffff"
        android:gravity="center"
        android:layout_gravity="center"
        />
    <ImageButton
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="@mipmap/search"
        android:layout_gravity="center"
        android:layout_marginRight="10dp"
        />
</LinearLayout>

具体的代码就已经完成了,这里的切换只能通过手动点击下面的标签进行切换,在接下来的学习中我们还会实现一个模仿微信的界面切换,他是可以通过点击选择切换,也可以选择滑动界面进行切换点击+滑动切换界面;如果需要该Demo源码的请点击源码下载,里面有所有图标的资源。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值