Fragment的基本使用

一. Fragment 的常用方法

方法介绍
add()添加Fragment
replace替换Fragment
remove()移除Fragment
hide()隐藏Fragment
show()显示Fragment

二. Fragment 的使用

  1. 为将要创建的Fragment准备布局一个布局: layout_fragment
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#345467">

    <TextView
        android:id="@+id/textView_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是MyFragment的布局"
        android:textColor="#ffffff"
        android:textSize="18sp"/>

</LinearLayout>
  1. 创建一个类MyFragment 继承Fragment, 并重写onCreateView方法:
public class MyFragment extends Fragment {  //继承Fragment
    @Nullable //注释 可为空
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    
        View root = inflater.inflate(R.layout.layout_fragment, container, false);
        return root;
    }
}
  1. MainActivity 主界面, onCreate中
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 获取Fragment管理类
       FragmentManager fm = getSupportFragmentManager();

        // 进行本次管理(每次管理需要重新获得) transaction: 事务, 办理
        FragmentTransaction transaction = fm.beginTransaction();
        // 添加Fragment 参数1: 主布局中的容器, 参数2: fragment对象, 参数3: 别名
        transaction.add(R.id.frame_home, new MyFragment(), "f1");

        // 其他方法
//        transaction.replace(主布局中的容器, fragment对象);
//        transaction.remove(frament对象);
//        transaction.hide(frament对象);
//        transaction.show(frament对象);

        transaction.commit(); //开始执行
    }
}
  1. 主布局的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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/frame_home"
        android:layout_width="300dp"
        android:layout_height="200dp">
    </FrameLayout>
        
</LinearLayout>

效果图如下:
在这里插入图片描述

三. Fragment 的生命周期

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值