定义

片段表示活动中的行为或用户界面(UI)的一部分。您可以在一个活动中组合多个片段来构建一个多窗格UI,并且可以在多个活动中重用一个片段。


特性

可以将片段看作活动的模块部分,类似于子活动,您也可以在其他活动中使用它。

片段有自己的生命周期并接收自己的输入事件。
您可以在活动运行时添加或移除片段。
片段的核心逻辑在kotlin类中定义。
片段的UI在XML布局文件中定义。


为一个活动添加片段的步骤

  • 新建一个片段类 new -> Fragment -> Fragment(Blank)
  • 为片段视图充气(inflater)

    class BlankFragment : Fragment() {
      // 一种做法
      override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                                savedInstanceState: Bundle?): View? {
          // Inflate the layout for this fragment
          return inflater.inflate(R.layout.fragment_blank, container, false)
      }
    
      // 或者使用数据绑定来充气
      override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                                savedInstanceState: Bundle?): View? {
        
          // FragmentBlankBinding 是根据xml布局文件,编译器自动生成的类
          val binding = DataBindingUtil.inflate<FragmentBlankBinding>(inflater,
          R.layout.fragment_blank, container,false)
          return binding.root
      }
    }
  • 将片段加入到主活动对应的xml布局文件中

     <LinearLayout>
       <fragment
          android:id="@+id/blankFragment"
    
          // 此处写对应类的具体包名
          android:name="com.example.android.navigation.BlankFragment"  
          // 或者写下面这句,这句是根本,上句会产生下句
          class = "com.example.android.navigation.BlankFragment" 
    
          android:layout_width="match_parent"
          android:layout_height="match_parent" />
    </LinearLayout>
最后修改:2020 年 05 月 27 日
如果觉得我的文章对你有用,请随意赞赏