Fragment基础知识

一、Fragment 介绍

Fragment是Android3.0后引入的一个新的API,他出现的初衷是为了适应大屏幕的平板电脑, 当然现在他仍然是平板APP UI设计的宠儿,而且我们普通手机开发也会加入这个Fragment, 我们可以把他看成一个小型的Activity,又称Activity片段!想想,如果一个很大的界面,我们 就一个布局,写起界面来会有多麻烦,而且如果组件多的话是管理起来也很麻烦!而使用Fragment 我们可以把屏幕划分成几块,然后进行分组,进行一个模块化的管理!从而可以更加方便的在 运行过程中动态地更新Activity的用户界面!另外Fragment并不能单独使用,他需要嵌套在Activity 中使用,尽管他拥有自己的生命周期,但是还是会受到宿主Activity的生命周期的影响,比如Activity 被destory销毁了,他也会跟着销毁!。

Fragment为什么被称为第五大组件?

Fragment的使用次数是不输于其他四大组件的,而且Fragment有自己的生命周期,比Activity更加节省内存。

Fragment的优势有以下几点:

模块化(Modularity):我们不必把所有代码全部写在Activity中,而是把代码写在各自的Fragment中。
可重用(Reusability):多个Activity可以重用一个Fragment。
可适配(Adaptability):根据硬件的屏幕尺寸、屏幕方向,能够方便地实现不同的布局,这样用户体验更好。

二、Fragment的生命周期

在这里插入图片描述

三、Fragment的创建

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
内部执行的顺序是:
(1).定义一个类, 继承Fragment
(2).重写父类的方法onCreateView()
(3).在onCreateView()方法中, 为Fragment 创建UI界面

四、Fragment的两种加载方式

静态加载

在这里插入图片描述
在需要加载fragment的activity中,想使用TextView一样,直接创建一个fragment即可.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="match_parent"
    android:orientation="vertical"
    tools:context=".Main2Activity">

    <fragment
        android:id="@+id/frag1"
        android:name="com.example.day005.SendFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></fragment>
   
</LinearLayout>

动态加载

动态加载也就是在java代码中创建fragment.

在这里插入图片描述
实现流程
1:获得FragmentManager对象
FragmentManager fragmentManager=getSupportFragmentManager();
2:开启事务
FragmentTransaction transaction = fragmentManager.beginTransaction();
3:通过FragmentTransaction 调用add()、replace()方法管理fragment
4:transaction .commit();

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1,创建fragment的管理对象
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        //2,获取fragment的事物对象,并开启事务
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        //3,调用事务中相应的方法,来操作fragment
        //add方法参数,第一个要放入的容器(布局的Id),第二个是fragment对象
        fragmentTransaction.add(R.id.main_layout_id,new MyFragment());
        //4,提交事务
        fragmentTransaction.commit();
    }
}

add,remove,replace,hide 方法

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1,创建fragment的管理对象
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        //2,获取fragment的事物对象,并开启事务
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        //3,调用事务中相应的方法,来操作fragment
        //add方法参数,第一个要放入的容器(布局的Id),第二个是fragment对象
         MyFragment myFragment = new MyFragment();
        fragmentTransaction.add(R.id.main_layout_id,myFragment);
        //移除一个Fragment
        fragmentTransaction.remove(myFragment);
        OneFragment oneFragment = new OneFragment(); //实例化一个Fragment对象
        //replace(替换一个布局)执行过程是先 remove 然后在 add.
        fragmentTransaction.replace(R.id.main_layout_id,oneFragment);
        //隐藏一个Fragment
        fragmentTransaction.hide(oneFragment);
        //4,提交事务
        fragmentTransaction.commit();

    }
}

五、案例

在这里插入图片描述在这里插入图片描述

xml文件代↓(代码内含有选择器,代码内并未放上)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="match_parent"
    android:orientation="vertical"
    tools:context=".Main2Activity">

    <LinearLayout
        android:id="@+id/ll"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_weight="9"
        android:layout_height="0dp"></LinearLayout>

    <RadioGroup
        android:id="@+id/rg"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="0dp"
        android:layout_weight="1.5"
        >
        <RadioButton
            android:id="@+id/person"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:drawableTop="@drawable/pic_select"
            android:layout_height="wrap_content"
            android:button="@null"
            android:gravity="center"
            android:checked="true"
            android:layout_marginTop="20dp"
            android:textColor="@drawable/text_color_select"
            android:text="联系人"></RadioButton>
        <RadioButton
            android:id="@+id/info"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:gravity="center"
            android:drawableTop="@drawable/pic_select"
            android:layout_height="wrap_content"
            android:button="@null"
            android:layout_marginTop="20dp"
            android:textColor="@drawable/text_color_select"
            android:text="信息"></RadioButton>
    </RadioGroup>
</LinearLayout>

联系人person的Fragment,XML代码

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".PersonFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="联系人" />

</FrameLayout>

信息Info的Fragment,XML代码

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".InfoFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="信息" />

</FrameLayout>

Main2Activity代码

package com.example.day004;

import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class Main2Activity extends AppCompatActivity {

    private LinearLayout ll;
    private RadioGroup rg;
    private RadioButton person;
    private RadioButton info;
    PersonFragment personFragment;
    InfoFragment infoFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        initView();

         personFragment = new PersonFragment();
         infoFragment = new InfoFragment();
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.ll,personFragment);
        fragmentTransaction.add(R.id.ll,infoFragment);
        fragmentTransaction.hide(infoFragment);
        fragmentTransaction.commit();

        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    //显示联系人 信息
                    case R.id.person:
                        FragmentManager supportFragmentManager = getSupportFragmentManager();
                        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
                        fragmentTransaction.hide(infoFragment);
                        fragmentTransaction.show(personFragment);
                        fragmentTransaction.commit();
                        break;
                    case R.id.info:
                        FragmentManager supportFragmentManager1 = getSupportFragmentManager();
                        FragmentTransaction fragmentTransaction1 = supportFragmentManager1.beginTransaction();
                        fragmentTransaction1.hide(personFragment);
                        fragmentTransaction1.show(infoFragment);
                        fragmentTransaction1.commit();
                        break;
                }
            }
        });

    }

    private void initView() {
        ll = (LinearLayout) findViewById(R.id.ll);
        rg = (RadioGroup) findViewById(R.id.rg);
        person = (RadioButton) findViewById(R.id.person);
        info = (RadioButton) findViewById(R.id.info);
    }
}

InfoFragment代码

package com.example.day004;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class InfoFragment extends Fragment {


    public InfoFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_info, container, false);
    }

}

PersonFragment代码

package com.example.day004;
package com.example.day004;


import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple {@link Fragment} subclass.
 */
public class PersonFragment extends Fragment {


    public PersonFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_person, container, false);
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值