美文网首页四大组件
Fragment(二)——Fragment静态使用详解

Fragment(二)——Fragment静态使用详解

作者: 奔跑的佩恩 | 来源:发表于2019-07-08 22:42 被阅读0次

前言

在上一篇中,我们对Fragment有一个初步的认识,了解了Fragment的生命周期。那么这一节,我们来详细讲讲Fragment的静态使用。

今天涉及的内容有:

  1. 静态Frament 使用前的描述
  2. 静态Frament 的创建
  3. 静态Frament 在activity_main.xml文件中的引用
  4. 静态Frament在MainActivity中的初始化
  5. 静态Frament的一些使用

先来波效果图


1.gif

一.静态Frament 使用前的描述

按我平常的习惯的话,这里应该是直接就进行知识的讲解了,但是由于很郁闷,于是在写之前就有这段话了。大多数文章对静态Frament 使用使用都是这样描述的:Fragment的静态使用非常简单,接着文章中对Fragmnet的静态使用就真的简单的描述了下,简单到什么程度呢:就是对其使用的讲解都只是讲一个开头就结束了,甚至有的都不讲,就一句话:Fragment的静态使用非常简单。所以,我有些郁闷。

二.静态Frament 的创建

ok,进入正题,静态Frament 的创建主要分两步:

  • 继承Fragment,重写Fragment的 onCreateView 生命周期,这里主要是为了加载Fragment的布局
  • 在重写的Fragment中进行必要初始化及相关方法,逻辑编写。
    下面以TitleFragment为例,TitleFragment继承于Fragment,其完整代码如下:
public class TitleFragment extends Fragment {

    private View mLayoutView;
    private TextView mTvText;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //加载布局
        mLayoutView = inflater.inflate(R.layout.frament_title, container, false);

        //初始化
        initView();
        initData();
        setListener();

        return mLayoutView;
    }

    private void initView(){
        mTvText=mLayoutView.findViewById(R.id.tv_fr_title);
    }

    private void initData(){

    }

    private void setListener(){

    }

    /**设置标题**/
    public void setTitle(String msg) {
        if (StringUtil.isNotEmpty(msg)) {
            mTvText.setText(msg);
        }
    }

}

TitleFragment对应的布局frament_title.xml代码很简单,就是在布局中加了一个TextView控件,具体如下

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/red"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/tv_fr_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:text="Hello World!"
        android:textColor="#000000"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

三.静态Frament 在activity_main.xml文件中的引用

相关文章

网友评论

    本文标题:Fragment(二)——Fragment静态使用详解

    本文链接:https://www.haomeiwen.com/subject/rjczhctx.html