【Android】Fragment的添加

上一篇文章学到了碎片的创建与生命周期,接下来学习碎片的常用操作,其中会用到上一篇文章的三个碎片,就做一个简单的说明吧:LeftFragment(包含一个按钮)、RightFragment4(以粉色为背景的文本,并在这个碎片中写了所有的回调方法)、AnotherRightFragment(以紫色为背景的文本)

FragementManager

每一个Activity都有一个Fragement Manager,用来管理它所包含的Fragement,在使用支持库的时候,使用getSupport-FragmentManager方法来访问Fragement Manager

添加Fragement到Activity中

知识点部分

Fragment的添加

在上一篇当中提到动态地添加碎片,使用是replace()方法,但它其实是碎片的替换方法替换当前的 Fragment 为一个新的 Fragment。真正的添加方法为add()。在一个容器当中可以添加多个Fragment,它们依次盖在上面,类似于FrameLayout。

Fragment的查找

删除与替换的前提都是这个碎片先找到,此时我们使用fragmentManager.findFragmentById(R.id.fcv)fragmentManager.findFragmentByTag("hhh"),根据这两个方法查找到最上面的一个,如果没有,则从BackStack里找,并返回最先添加的一个,如果没有,返回null

Fragment的移除

fragmentTransaction.remove(fragment).commit()方法移除,依次移除当前容器最上面的一个Fragment,但只是将其从容器中移除,backStack里仍然存在,使用查找方法仍可以找到,只不过它的状态是不可见的,需要按下返回键才能彻底移除

Fragment的替换

fragmentTransaction.replace(R.id.fcv, LeftFragment.class, null)当没有addToBackStack会将容器上的所有碎片进行移除,添加新的Fragment。此时BackStack里的Fragment仍然存在,按下返回键依然会响应到BackStack,即弹出BackStack里的Fragment,此时我们看到的是替换的碎片,但是看着好像什么都没有发生。

Fragment的显示与隐藏

show、hide:只是把Fragment显示/隐藏,Fragment的生命周期不发生变化,相当于View的显示/隐藏

attach、detach:把Fragment从容器中移除/装载,Fragment的生命周期发生变化,执行到onDestroyView,其View被销毁,但Fragment仍存在

体验

接下来就体验一下吧:

首先我们创建一个新的活动,其中我们在布局里面放入一个碎片容器以及各种操作的按钮,布局文件代码:

<LinearLayout 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:orientation="vertical"
    tools:context=".FragmentAdd">

    <androidx.fragment.app.FragmentContainerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:id="@+id/fcv"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/add1"
        android:text="add1"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/add2"
        android:text="add2"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/remove1"
        android:text="remove1"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/remove2"
        android:text="remove2"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/replace"
        android:text="replace"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/show"
        android:text="show"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/hide"
        android:text="hide"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/attach"
        android:text="attach"/>

    <Button
        android:id="@+id/detach"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="detach" />

</LinearLayout>

主要是在主活动里的代码:

public class FragmentAdd extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_fragment_add);
        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;
        });
        Button buttonadd1 = (Button) findViewById(R.id.add1);
        buttonadd1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addFragment1(FragmentAdd.this.getCurrentFocus());
            }
        });

        Button buttonadd2 = (Button) findViewById(R.id.add2);
        buttonadd2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addFragment2(FragmentAdd.this.getCurrentFocus());
            }
        });

        Button buttonremove1 = (Button) findViewById(R.id.remove1);
        buttonremove1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removefragment1(FragmentAdd.this.getCurrentFocus());
            }
        });

        Button buttonremove2 = (Button) findViewById(R.id.remove2);
        buttonremove2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removefragment2(FragmentAdd.this.getCurrentFocus());
            }
        });

        Button buttonreplace = (Button) findViewById(R.id.replace);
        buttonreplace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                replacefragment(FragmentAdd.this.getCurrentFocus());
            }
        });

        Button buttonshow = (Button) findViewById(R.id.show);
        buttonshow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showfragment(FragmentAdd.this.getCurrentFocus());
            }
        });

        Button buttonhide = (Button) findViewById(R.id.hide);
        buttonhide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hidefragment(FragmentAdd.this.getCurrentFocus());
            }
        });

        Button buttonattach = (Button) findViewById(R.id.attach);
        buttonattach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                attachfragment(FragmentAdd.this.getCurrentFocus());
            }
        });

        Button buttondetach = (Button) findViewById(R.id.detach);
        buttondetach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                detachfragment(FragmentAdd.this.getCurrentFocus());
            }
        });
    }

    public void addFragment1 (View view) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.fcv, RightFragment4.class, null, "添加碎片")
                .addToBackStack("hhh")
                .setReorderingAllowed(true)
                .commit();
    }

    public void addFragment2 (View view) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        AnotherRightFragment anotherRightFragment = new AnotherRightFragment();
        fragmentTransaction.add(R.id.fcv, anotherRightFragment).commit();
    }

    public void removefragment1 (View view) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragment = fragmentManager.findFragmentById(R.id.fcv);
        Log.d("查找碎片", "查找的顶端碎片" + fragment.toString());
        fragmentTransaction.remove(fragment).commit();
    }

    public void removefragment2 (View view) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragment = fragmentManager.findFragmentByTag("添加碎片");
        Log.d("查找碎片", "根据Tag查早的碎片" + fragment.toString());
        fragmentTransaction.remove(fragment).commit();
    }

    public void replacefragment(View view) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fcv, LeftFragment.class, null).commit();
    }

    public void showfragment(View view) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragment = fragmentManager.findFragmentById(R.id.fcv);
        if (fragment != null) {
            fragmentTransaction.show(fragment).commit();
        }
    }

    public void hidefragment(View view) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragment = fragmentManager.findFragmentById(R.id.fcv);
        if (fragment != null) {
            fragmentTransaction.hide(fragment).commit();
        }
    }

    Fragment fragmenthh;
    public void attachfragment(View view) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        /*Fragment fragment = fragmentManager.findFragmentById(R.id.fcv);*/
        if (fragmenthh != null) {
            fragmentTransaction.attach(fragmenthh).commit();
        }
    }

    public void detachfragment(View view) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmenthh = fragmentManager.findFragmentById(R.id.fcv);
        if (fragmenthh != null) {
            fragmentTransaction.detach(fragmenthh).commit();
        }
    }
}

添加:为所有的按钮注册了点击事件,两种不同的添加方式,第一种我们添加进去粉色底色的文本,按下第二个按钮就会添加进去一个紫色的文本,两种添加方式也不同,第一个添加方式采用上一篇内容的模拟返回栈内容,当你按下第一个按钮会看到这样的界面:

在这里插入图片描述

此时按下add2按钮,采用第二种方式添加碎片,界面发生了变化:

在这里插入图片描述

此时我们只能看到第二个碎片,碎片的添加方式是叠加的,此时查看到底有多少个碎片:

在这里插入图片描述

就可以看到此时共有两个碎片,在返回栈当中只有一个碎片,因为只有第一个按钮是将添加的碎片也加入到返回栈当中,此时按下Back按钮会看到页面没有发生任何的变化,此时是将返回栈当中的第一个碎片取出来,再次按下Back键,就会退出这个活动。

思考一下,如果我再次按下第一个按钮,将第一个碎片再次加入到活动当中,此时按下Back键会发生什么,按多少次Back按钮才会退出这个活动呢?

此时我们明白,返回栈当中有两个粉色的碎片,当第一次按下Back按钮,最上面的粉色碎片就会从返回栈当中移除,此时界面为紫色,之后返回栈当中就只剩下一个碎片了与上面的情况一样。因此我们一共需要按3次Back按钮才会退出活动。

查找与删除:我们依次添加四个碎片,此时有两个进入了栈里面,此时页面为紫色碎片的样子

在这里插入图片描述

此时按下第一个移除键,删除的是活动顶部的碎片,紫色碎片被移除,页面为粉色的碎片,查看日志的打印信息:

在这里插入图片描述

可以看到删除的就是顶部的碎片,此时按下remove2,会页面没有发生变化,但我们知道是因为有两个一样的碎片,再次按下remove2,会看到页面变回了紫色,此时查看打印日志:

在这里插入图片描述

再次按下remove1,我们知道碎片已经移除完毕了,此时页面没有任何的碎片,再次按下删除键,此时不会进行移除操作,但会去返回栈寻找最底部即第一次添加的碎片。

替换:重新运行程序,添加几个碎片到活动当中,此时查看含有的碎片:
在这里插入图片描述

按下replace按钮,被替换成了另一个含有按钮的碎片:

在这里插入图片描述

此时查看有多少个碎片:
在这里插入图片描述

此时可以看到活动内所有的碎片都被去除,由新的碎片替代,我们看到栈当中并未有任何的改变,栈内只能由Back键进行操作,此时活动只剩下这一个碎片。

显示与隐藏

在上篇文章中提到我们给RightFragment4添加了回调方法,因此此处使用这个碎片,此时按下hide按钮,我们看到页面发生了变化,由粉色变为了紫色,此时打印日志并没有发生任何的变化。再次按下show按钮,粉色显示出来了,此时打印日志还是没有发生任何的变化。

接下来按下detach按钮,页面与按下hide按钮的效果相同,此时的打印日志:

在这里插入图片描述

当我们attach()的时候这个碎片必须是已经创建好的,但是未与活动创建联系,我们这里将detach的碎片记录下来,这个碎片经过detach()方法与活动解除了联系,再调用attach()方法此时刚才的碎片又显示出来了

到这里就结束了!

  • 12
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值