Android Fragment用法详解(2)--动态添加Fragment

Android Fragment详解 一、什么是Fragment? Fragment:是Android3.0开始新增的概念,意为碎片。Fragment是依赖于Activity的,不能独立存在的。 二、为什么要有Fragment? Android运行在各种各样的设备中,有小屏幕的手机,还有大屏幕的平板,电视等。同样的界面在手机上显示可能很好看,在大屏幕的平板上就未必了,手机的界面放在平板上可能会有过分被拉长、控件间距过大等情况。针... 阅读详情

Android Fragment用法详解(2)–动态添加Fragment

在上一篇文章《Android Fragment用法详解(1)–静态使用Fragment》我们讲解了Fragment的最简单的用法。这次我们来说一说Fragment复杂一丢丢的用法。在代码中动态添加Fragment,让其实现类似微信主页面效果。也就是点击底部的按钮来动态改变中间内容页面。我们先来看看效果图吧。说明一下,为了方便大家复制粘贴,里面没有任何图片素材,都是用颜色和安卓自带图片来现实效果,所以有点难看哈~~毕竟我们是程序员不是美工嘛!
这里写图片描述
接下来就是源代码啦

先看MainActivity的布局文件吧。因为布局文件是关键哦。

<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:orientation="vertical" >

    <!-- 把Fragment当作普通控件使用,这里没啥作用,就是作为一个标题栏,不用Fragment,直接写布局一样的 -->
    <fragment
        android:id="@+id/fg_title"
        android:name="com.example.fragmentdemo.TitleFragment"
        android:layout_width="match_parent"
        android:layout_height="45dp" />

    <!-- 用一个帧布局来占一个位置,目的是给fragment用 -->
    <FrameLayout
        android:id="@+id/fl_content"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >
    </FrameLayout>

    <!-- 底部三个按钮,我们用RadioGroup来实现 -->
    <include layout="@layout/bar" />

</LinearLayout>

然后看看底部四个按钮的布局吧

<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/rg"
    android:orientation="horizontal" >

    <!-- android:paddingLeft="0dp"加这个是为了让内容能够剧中 -->
    <RadioButton
        android:id="@+id/rb_1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/bar_selector"
        android:button="@null"
        android:drawableTop="@android:drawable/star_on"
        android:gravity="center"
        android:paddingLeft="0dp"
        android:text="Frag_1" />

    <RadioButton
        android:id="@+id/rb_2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/bar_selector"
        android:button="@null"
        android:drawableTop="@android:drawable/star_on"
        android:gravity="center"
        android:paddingLeft="0dp"
        android:text="Frag_2" />

    <RadioButton
        android:id="@+id/rb_3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/bar_selector"
        android:button="@null"
        android:drawableTop="@android:drawable/star_on"
        android:gravity="center"
        android:paddingLeft="0dp"
        android:text="Frag_3" />

</RadioGroup>

然后就是三个按钮的选择器(就是控制点击底部按钮的时候,底部按钮能够变化背景颜色的选择器)

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android" >  
    <item android:state_checked="true" android:drawable="@android:color/holo_red_light" ></item>  
    <item android:state_checked="false" android:drawable="@android:color/holo_blue_bright"></item>  
</selector>  

接下来就是先上一些无关紧要的文件,哈哈。标题栏的类文件和布局文件

先看布局文件

<?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="45dp"
    android:gravity="center"
    android:background="#00ff00" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment制作的标题栏"
        android:textColor="@android:color/black"
        android:textSize="18sp" />

</RelativeLayout>

然后是类文件

package com.example.fragmentdemo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 *************************************************************** 
 * 
 * @版权 LinFeng
 * 
 * @作者 LinFeng
 * 
 * @版本 1.0
 * 
 * @创建日期 2016-6-6
 * 
 * @功能描述 用Fragment制作标题栏
 ***************************************************************** 
 */
public class TitleFragment extends Fragment{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        /**
         * 加载布局文件然后返回view,显示在Activity
         */
        View view = inflater.inflate(R.layout.title, container,false);
        return view;
    }

}
package com.example.fragmentdemo;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class MainActivity extends FragmentActivity implements OnClickListener {

    private RadioButton rb1;
    private RadioButton rb2;
    private RadioButton rb3;

    private RadioGroup rGroup;

    private Fragment f1,f2,f3;
    private FragmentManager manager;
    private FragmentTransaction transaction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        /**
         * 拿到事务管理器并开启事务
         */
        manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();

        /**
         * 初始化按钮
         */
        rb1 = (RadioButton) findViewById(R.id.rb_1);
        rb2 = (RadioButton) findViewById(R.id.rb_2);
        rb3 = (RadioButton) findViewById(R.id.rb_3);

        rGroup = (RadioGroup) findViewById(R.id.rg);

        /**
         * 为三个按钮添加监听
         */
        rb1.setOnClickListener(this);
        rb2.setOnClickListener(this);
        rb3.setOnClickListener(this);

        /**
         * 启动默认选中第一个
         */
        rGroup.check(R.id.rb_1);
        f1 = new Fragment1();
        transaction.replace(R.id.fl_content, f1);
        transaction.commit();
    }

    @Override
    public void onClick(View v) {

        manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();

        switch (v.getId()) {
            case R.id.rb_1 :
                /**
                 * 为了防止重叠,需要点击之前先移除其他Fragment
                 */
                hideFragment(transaction);
                f1 = new Fragment1();
                transaction.replace(R.id.fl_content, f1);
                transaction.commit();

                break;
            case R.id.rb_2 :
                hideFragment(transaction);
                f2 = new Fragment2();
                transaction.replace(R.id.fl_content, f2);
                transaction.commit();

                break;
            case R.id.rb_3 :
                hideFragment(transaction);
                f3 = new Fragment3();
                transaction.replace(R.id.fl_content, f3);
                transaction.commit();
                break;

            default :
                break;
        }
    }

    /*
     * 去除(隐藏)所有的Fragment
     * */
    private void hideFragment(FragmentTransaction transaction) {
        if (f1 != null) {
            //transaction.hide(f1);隐藏方法也可以实现同样的效果,不过我一般使用去除
            transaction.remove(f1);
        }
        if (f2 != null) {
            //transaction.hide(f2);
            transaction.remove(f2);
        }
        if (f3 != null) {
            //transaction.hide(f3);
            transaction.remove(f3);
        }


    }

}

到这里基本都结束了。哈哈,然后聪明的同学一定还注意到MainActivtiy里还有3个Fragment的类,由于这三个基本是99%相同的,所以我就贴出其中一个的代码(其他两个无非就是修改显示文字,类文件名而已~~其他全部相同)

先看类文件

package com.example.fragmentdemo;

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

/**
 *************************************************************** 
 * 
 * @版权 LinFeng
 * 
 * @作者 LinFeng
 * 
 * @版本 1.0
 * 
 * @创建日期 2016-6-6
 * 
 * @功能描述 
 ***************************************************************** 
 */

/**
 * 这里要注意,Fragment是要引入android.support.v4.app.Fragment这个包里面的,不是那个app.fragment那个包哦
 * @author LinFeng
 *
 */
public class Fragment1 extends Fragment{

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

}

然后是布局文件

<?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:background="#ffff00"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="25sp"
        android:text="FRAGMENT_1" />

</LinearLayout>

看到这里,相信大家基本都学会动态添加Fragment了吧!为什么不直接贴出项目代码给大家下载?主要是,我不建议大家直接下载人家的项目来运行,然后阅读,感觉你会了。但其实,如果自己写,可能会出现各种奇葩的问题,所以,根据人家的思路,自己写一遍,运行一下,出来的,才是你自己的。

《==================================这是一条华丽的分割线================================》

最后我们看一些关于Fragment的东西,刚刚好在人家的博客里面看到觉得不错就COPY过来给大家看看了。

a、获取FragmentManage的方式:

getFragmentManager() // v4中,getSupportFragmentManager

b、主要的操作都是FragmentTransaction的方法

FragmentTransaction transaction = fm.benginTransatcion();//开启一个事务

transaction.add()

往Activity中添加一个Fragment

transaction.remove()

从Activity中移除一个Fragment,如果被移除的Fragment没有添加到回退栈(回退栈后面会详细说),这个Fragment实例将会被销毁。

transaction.replace()

使用另一个Fragment替换当前的,实际上就是remove()然后add()的合体~

transaction.hide()

隐藏当前的Fragment,仅仅是设为不可见,并不会销毁

transaction.show()

显示之前隐藏的Fragment

detach()

会将view从UI中移除,和remove()不同,此时fragment的状态依然由FragmentManager维护。

attach()

重建view视图,附加到UI上并显示。

transatcion.commit()//提交一个事务

注意:常用Fragment的哥们,可能会经常遇到这样Activity状态不一致:State loss这样的错误。主要是因为:commit方法一定要在Activity.onSaveInstance()之前调用。

上述,基本是操作Fragment的所有的方式了,在一个事务开启到提交可以进行多个的添加、移除、替换等操作。

值得注意的是:如果你喜欢使用Fragment,一定要清楚这些方法,哪个会销毁视图,哪个会销毁实例,哪个仅仅只是隐藏,这样才能更好的使用它们。

a、比如:我在FragmentA中的EditText填了一些数据,当切换到FragmentB时,如果希望会到A还能看到数据,则适合你的就是hide和show;也就是说,希望保留用户操作的面板,你可以使用hide和show,当然了不要使劲在那new实例,进行下非null判断。

b、再比如:我不希望保留用户操作,你可以使用remove(),然后add();或者使用replace()这个和remove,add是相同的效果。

c、remove和detach有一点细微的区别,在不考虑回退栈的情况下,remove会销毁整个Fragment实例,而detach则只是销毁其视图结构,实例并不会被销毁。那么二者怎么取舍使用呢?如果你的当前Activity一直存在,那么在不希望保留用户操作的时候,你可以优先使用detach。

Android学习|Fragment__01静态、动态添加Fragment 什么是Fragment 1:具备生命周期 Fragment有生命周期,那么在一个activity可以使用多个Fragment,或者一个Fragment在多个activity 中重复使用,来完成一些效果 2、必须委托在activity中才能运行 则一个activity暂停,其中包含的所有的Framgment都会暂停 动态添加Fragment ... 阅读详情

相关推荐

Android之Fragment动态添加和移除Fragment

fragment_demo.xml&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_hei...

qq_38922435的博客 6168

FragmentTabHost如何设置tab选中状态

mHomeTabHost.setCurrentTab(0);//设置tabhost当前被选中 0表示第一个tab

wolfking0608的博客 1566

(八)安卓开发中的Fragment使用详解

Fragment是 Android 中的一种 UI 组件,代表 Activity 中的一个行为或一个 UI 部分。你可以将其看作是 Activity 的一个模块,具有自己的生命周期,并且可以独立于 Activity 存在。Fragment 的设计初衷是为了支持更大屏幕的设备(例如平板电脑),通过在同一个 Activity 中显示多个 Fragment,可以更高效地利用屏幕空间。

cuijiying的博客 1585

首页Fragment切换

现在基本所有app首页都是下边3、4个tab,点击实现上面fragment的切换。一直用到,就把这个封装成一个控件。 首先下面的tab有图标和文字,直接用textviwe设置drawableTop图片的尺寸间距什么的用起来不方便。就自定义个ImgText继承LinearLayout,里面就一个ImageView和一个TextView,然后有个设置默认图片,选中图片,文字,默认颜色,选中颜色等方法。

renshaodong的博客 583

安卓APP_ Fragment(1)—— Fragment概念、基础用法、动态变换、管理栈

Fragment一、Fragment是什么Fragment的产生原因Fragment两个重要特性具备生命周期寄宿在Activity中运行二、Fragment基础用法简单演示(1)New创建一个Activity(2)添加一个空白的Fragment(3)Fragment 绑定到宿主Activity(4)在Activity中创建两个Fragment具体细节在代码中呈现 一、Fragment是什么 Fragment的产生原因 Fragment很像是小的,简短的Activity。 Fragment在安卓3.0后才开始

华天朱 720

机器学习实例(预测房价中位数)(附代码)

1、下载数据: 下载一个压缩文件housing.tgz即可,其包含housing.csv(已经包含书有数据。),用 tax xzf housing.tgz 来解压提取CSV文件。 import os import tarfile import urllib.request DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml2/master/" HOUSING_PATH = os.path.join("datasets",

qq_51153436的博客 2769

Android studio心得——fragment动态加载

4.增加Fragment1到Fragment4的碎片布局,布局中只有一个TextView,分别设置文本为页面一到页面四,如图完成fragment_wx.xml、fragment_txl.xml、fragment_fx.xml、fragment_w.xml..2.如果使用静态加载,上面的主视图布局只能加载一个碎片,不能实现动态切换的功能;这种情况下需要使用动态加载的功能,如图所示,页面1~页面4是4个不同的Fragment,在功能键进行切换的时候,Activity主视图动态加载对应的碎片进行切换。

2301_77275933的博客 3855

LabVIEW状态机实战:用STM32+DHT11搭建温湿度监测系统(附完整VI源码)

本文详细介绍了如何利用LabVIEW状态机模式与STM32微控制器、DHT11温湿度传感器构建温湿度监测系统。通过硬件选型、状态机设计、LabVIEW程序实现及系统优化等环节,提供了一套完整的解决方案,并附有VI源码,助力开发者快速实现嵌入式温湿度监测应用。

weixin_42549723的博客 525

Android Fragment

原文地址:http://my.oschina.net/u/556624/blog/103494 http://blog.csdn.net/aomandeshangxiao/article/details/7671533 Fragment是activity的界面中的一部分或一种行为。你可以把多个Fragment们组合到一个activity中来创建一个多面界面并且你可以在多个activity中重用

winson_jason的专栏 1900

mac(apple silicon)arm64安装spm12详细教程

3.下载matlab runtime R2023b for macOS (macA64),注意必须下载这个,只下载matlab是不可以的。默认安装目录是/Applications/MATLAB/MATLAB_Runtime/R2023b。注意最后的命令,路径根据自己的matlab_runtime安装位置进行调整,然后就可以安装成功了。5. 解压spm12.zip,解压后将文件夹拖到应用程序下(Applications)2.下载spm12,这个版本可兼容mac芯片!6.打开mac终端,输入。

weixin_62332001的博客 2036

告别ROS1!在Ubuntu 22.04上为VINS-Fusion适配ROS2 Humble的完整踩坑记录

本文详细记录了在Ubuntu 22.04上将VINS-Fusion从ROS1迁移到ROS2 Humble的完整过程,包括环境搭建、依赖管理、核心代码适配及性能优化。通过实战案例和调试技巧,帮助开发者高效解决迁移过程中的常见问题,提升系统稳定性和性能。

weixin_42628688的博客 288

Android studio 动态fragment的用法

Android studio:动态fragment的用法 fragment的使用时Android的基础,它有两种用法,第一个就是静态的fragment。第二个则是动态的fragment。 静态fragment直接在layout创建你想要的fragment的XML的文件,然后在你的Java包里面创建对应fragment的class文件 布局代码如下所示 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="h

weixin_45934604的博客 3050

RAW、RGB、YUV图像格式的采样与存储原理详解

本文详细解析了RAW、RGB和YUV三种核心图像格式的采样与存储原理。RAW是传感器原始数据,信息完整但需后期处理;RGB直接对应显示,直观但数据量大;YUV通过亮色分离与色度下采样,在保证观感的前提下大幅提升传输与存储效率,是视频编码与流媒体的主流格式。理解其差异是图像处理与视频开发的基础。

e4f5g6h7的博客 523

Android动态添加Fragment

Android动态添加Fragment 效果图如下: 项目结构图如下: Fragment1: package com.demo.dongtaifragment; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.NonNull; import andr...

AndroidStudyDay的博客 2637

(代码可运行)半导体器件和工艺模拟 使用Silvaco设计构建NMOS并提取各项工艺及器件参数

win10。

qq_20388971的博客 114

[Dify实战] 用 Dify 打造高效的新员工 7 天成长计划-带绑定资源

本文介绍了如何利用Dify平台为新员工制定智能成长计划,解决融入难、节奏乱、成长慢等问题。方案通过输入岗位信息自动生成7天结构化计划,包含每日任务和评估要点,并支持进度跟踪与报告输出。关键点在于设计清晰的Prompt模板,合理分配学习节奏,形成闭环反馈机制。该方案能显著提升新员工培养效率,实现人才培养的数字化升级。

技术小甜甜:传播可落地技术,帮助个人和企业降低解决真实场景问题的成本 577

Android之Fragment的动态添加

Fragment Fragment是Android3.0后引入的一个新的API,我们可以把它看成看成一个小型的Activity,又称Activity片段。Fragment有自己的生命周期但它仍需要嵌套在Activity 中使用,并且会受到Activity的生命周期的影响,比如Activity 被destory销毁了,他也会跟着销毁。 在Activity中添加Fragment有两种方式,一种是静态添加,一种是动态添加。 接下来主要讲一下动态添加: 1、创建三个fragment.xml布局文件,分别为:

m0_60746014的博客 7941

YOLOv8改进 | 融合篇,YOLOv8改进主干网络为MobileNetV3+CA注意机制+添加小目标检测层(全网独家首发,实现极限涨点)

小目标检测难点众多,导致很多算法对小目标的检测效果远不如大中型目标。影响算法性能的主要原因如下:第一,小目标分辨率低、信息量不足,导致神经网络提取到的有效特征较少。第二,小目标在图像中所占的区域较小,易受背景干扰,这对算法的定位性能要求较高。第三,小物体标注困难,训练数据有限,导致模型泛化能力差。例如多尺度学习、无锚机制和生成对抗学习等方法,都能提高小目标检测的准确性和鲁棒性。为了改善小目标漏检现象严重的问题,我在 YOLOv8 中增加了 P2 检测头,相当于有四个检测头,使网络能检测到更小的目标。

在职AI算法工程师,擅长计算机视觉,YOLO目标检测、分割等,擅长web、pyqt界面可视化,好内容持续更新中,来这里跟大家一起学习,共同进步 2862

android fragment动态添加,Android动态添加Fragment

效果图如下:项目结构图如下:Fragment1:package com.demo.dongtaifragment;import android.app.Fragment;import android.os.Bundle;import android.support.annotation.NonNull;import android.support.annotation.Nullable;impor...

weixin_36252577的博客 718

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

【Android】4.0Fragment的使用(动态添加与组件获取)

🍀【Android】4.0Fragment的使用

一个专注于客户端开发的技术er,不定期更新Android,Flutter,HormonyOS等方向的使用心得和感悟 2890

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

【Android】Fragment的添加

上一篇文章学到了碎片的创建与生命周期,接下来学习碎片的常用操作,其中会用到上一篇文章的三个碎片,就做一个简单的说明吧:LeftFragment(包含一个按钮)、RightFragment4(以粉色为背景的文本,并在这个碎片中写了所有的回调方法)、AnotherRightFragment(以紫色为背景的文本)每一个Activity都有一个Fragement Manager,用来管理它所包含的Fragement,在使用支持库的时候,使用getSupport-FragmentManager方法来访问Frageme

2301_79828182的博客 2296

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

android fragment动态加载,动态添加Fragment

8种机械键盘轴体对比本人程序员,要买一个写代码的键盘,请问红轴和茶轴怎么选?动态添加Fragment在程序运行时, 根据具体情况来动态地添加Fragment到Activity中.1 新建 AnotherRightFragment 作为另一个右侧Fragment . 并写好布局文件 another_right_fragment.xml.(黄色背景)import android.app.Fragme...

weixin_27130513的博客 1192

android的fragment用法,Android Fragment用法知识点的讲解

Android Fragment用法的讲解碎片,它的出现是为了更好展示UI的设计,让程序更加得到充分的展示。Fragment的出现,如微信的额主界面包含多个Fragment,使得微信功能更加简洁明了。Fragment组件Fragment是Android 3.0的时候被引入的,主要目的是为了给大屏幕(如平板电脑)添加动态和灵活的UI支持。利用Fragment实现更好的用户体验。Fragment加载静...

weixin_29454359的博客 1576
下一篇: Android开发:LayoutParams的用法
xueAnother
博客等级 码龄11年 3粉丝 17原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值