动态管理片段

来源:互联网 发布:淘宝彩票走势图 编辑:程序博客网 时间:2024/04/30 22:27

动态管理片段

 /**     * 片段可以重叠     * 添加片段     */    public void add(View view) {        //        FragmentManager fm = getSupportFragmentManager();        FragmentTransaction ft = fm.beginTransaction();        ft.add(R.id.fragment, new RedFragment());        ft.commit();    }    /**     * 删除当前布局上的片段     */    public void del(View view) {        FragmentManager fm = getSupportFragmentManager();        // 获取当前的片段对象        Fragment currentFragment = fm.findFragmentById(R.id.fragment);        if (currentFragment != null) {            FragmentTransaction ft = fm.beginTransaction();            ft.remove(currentFragment);            ft.commit();        }    }    /**     * 不管之前后没有都会替换掉     */    public void replace(View view) {        FragmentManager fm = getSupportFragmentManager();        FragmentTransaction ft = fm.beginTransaction();        ft.replace(R.id.fragment, new BlueFragment());        ft.commit();    }    /**     * 添加到回退栈     */    public void toBack(View view) {        FragmentManager fm = getSupportFragmentManager();        FragmentTransaction ft = fm.beginTransaction();        ft.replace(R.id.fragment, new RedFragment());        ft.addToBackStack(null);        ft.commit();    }
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.example.zxc.myapplication.MainActivity"><LinearLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal">        <Button            android:onClick="add"            android:text="添加"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/btn_add"/>        <Button            android:onClick="del"            android:text="删除"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/btn_del"/>        <Button            android:onClick="replace"            android:text="替换"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/btn_rep"/>        <Button            android:onClick="toBack"            android:text="添加到回退栈"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/btn_toback"/>    </LinearLayout>    <FrameLayout        android:id="@+id/fragment"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1"></FrameLayout></LinearLayout></RelativeLayout>

这里写图片描述

0 0
原创粉丝点击