碎片(Fragment)是一种可以嵌入在活动当中的UI片段,它能让程序更加合理和充分地利用大屏幕的空间,因而在平板上应用得非常广泛。
package com.example.fragmenttest;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.fragment.app.Fragment;public class RightFragment extends Fragment { //继承自Fragment@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {View view = inflater.inflate(R.layout.right_fragment, container, false); //调用onCreateView方法,使用Inflater.inflate方法加载right_fragmentreturn view;}}
动态注册碎片
5步:
(1) 创建待添加的碎片实例。
(2) 获取FragmentManager,在活动中可以直接通过调用getSupportFragmentManager()方法得到。
(3) 开启一个事务,通过调用beginTransaction()方法开启。
(4) 向容器内添加或替换碎片,一般使用replace()方法实现,需要传入容器的id和待添加的碎片实例。
(5) 提交事务,调用commit()方法来完成。
private void replaceFragment(Fragment fragment){FragmentManager fragmentManager = getSupportFragmentManager();//调用fragmentManager, 通过getSupportFragmentManager方法实现,得到实例FragmentTransaction transaction = fragmentManager.beginTransaction();//beginTransaction()开启一个事务transaction.replace(R.id.right_fragment, fragment);transaction.commit();}
