Android基础 ----- Fragment 之静/动态加载,滑动效果,生命周期

Fragment (碎片)

什么是Fragment
理论:简单来说,Fragment其实可以理解为一个具有自己生命周期的控件,只不过这个控件又有点特殊,它有自己的处理输入事件的能力,有自己的生命周期,又必须依赖于Activity,能互相通信和托管。
是一种可以嵌入在Activity中的 UI 片段,它能让程序更加合理和充分地利用大屏幕的空间,因而在平板和目前的大屏手机上应用的非常广泛
作用:可以实现Android界面的局部更新


1.关于Fragment静态加载和动态加载的实现与使用

(1)静态加载

什么是fragment的静态加载:是讲在主布局文件中放入fragment布局,然后使用

  • 1.在src下面创建两个fragment文件
    这里写图片描述

这里写图片描述

之后会生成两个fragment的布局文件,修改里面的布局

<?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=".RightFragment">

    <!-- TODO: Update blank fragment layout -->

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:layout_gravity="center"
        android:text="右边的fragment" />
</FrameLayout>
<?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"
    android:background="#00ff00"
    tools:context=".LeftFragment">

    <!-- TODO: Update blank fragment layout -->
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:id="@+id/button"
        android:layout_gravity="center"
        />

</FrameLayout>

然后在activity_main.xml中完成以上两个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"
tools:context="com.example.myapplication.MainActivity">

<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:name="com.example.myapplication.HelloFragment"
android:id="@+id/hello_fragment"/>

<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="@+id/list_fragment"
android:name="com.example.myapplication.ListFragment"/>

</LinearLayout>

效果

这里写图片描述


(2)动态加载

什么是动态加载:不需要在主布局文件中去声明fragment的,而是直接在java代码中去添加

  • 1.我们主布局activity_main.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"
    tools:context=".MainActivity">
<fragment
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:id="@+id/fragment_left"
    android:name="com.example.xiao.fragmentdemo.LeftFragment"
    ></fragment>
    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:id="@+id/fragment_right"
        android:name="com.example.xiao.fragmentdemo.RightFragment"
      ></fragment>


</LinearLayout>
  • 2.再创建两个fragment用于动态替换
    another_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=".anotherFragment"
    android:background="@color/colorAccent"
    >

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="a1"
        android:textSize="20sp"
        android:layout_gravity="center"
        />

</FrameLayout>

another_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=".another2kFragment"
    android:background="@color/colorPrimaryDark"
    >

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="a2"
        android:textSize="20sp"
        android:layout_gravity="center"
        />


</FrameLayout>
  • 3 为例测试动态切换,我们在left_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"
    android:background="#00ff00"
    tools:context=".LeftFragment">

    <!-- TODO: Update blank fragment layout -->
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="切换卡1"
            android:id="@+id/button1"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="切换卡2"
            android:id="@+id/button2"
            android:layout_below="@id/button1"
            />
    </RelativeLayout>


</FrameLayout>
  • 4.最后我们在MainActivity中整合逻辑,实现卡片切换
package com.example.xiao.fragmentdemo;

import android.app.Fragment;


import android.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
   android.support.v4.app.FragmentManager fragmentManager =null;
    FragmentTransaction tx = null;
    //实例化两个新创建的fragment
    anotherFragment a = new anotherFragment();
    another2kFragment a2 = new another2kFragment();
    Button button1 = null;
    Button button2 = null;


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


        init();
    }

    private void init() {
        //初始化数据,并为按钮添加监听
        button1 = findViewById(R.id.button1);
        button2 = findViewById(R.id.button2);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
    switch (v.getId()){
        case  R.id.button1:
            //点击按钮1可以实现切换为fragment1
            fragmentManager = getSupportFragmentManager();
            tx = fragmentManager.beginTransaction();
            tx.replace(R.id.fragment_right,a);
            break;

        case R.id.button2:
            //点击按钮二实现切换fragment2
            fragmentManager = getSupportFragmentManager();
            tx = fragmentManager.beginTransaction();
            tx.replace(R.id.fragment_right,a2);
            break;
        default:
            break;
    }
    tx.commit();  //提交事物
    }
}
  • 5 结构目录
    这里写图片描述

这里写图片描述


2.使用Fragment+Viewpager实现滑动效果

这里写图片描述

这里写图片描述

  • 1首先我们先建立三个Fragment(代码略,可以参考上面新建fragment的操作)

  • 2在activity_main.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"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1"
        >
        <TextView
            android:layout_width="0px"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="聊天"
            android:gravity="center"
            android:id="@+id/lay_charTop"
            />
        <TextView
            android:layout_width="0px"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="主页"
            android:gravity="center"
            android:id="@+id/lay_contentTop"
            />

        <TextView
            android:layout_width="0px"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="朋友圈"
            android:gravity="center"
            android:id="@+id/lay_friendsTop"
            />


    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="5px"
        >
        <View
            android:layout_width="0px"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:id="@+id/chars_bom"
            />
        <View
            android:layout_width="0px"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:id="@+id/content_bom"
            />
        <View
            android:layout_width="0px"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:id="@+id/frident_bom"
            />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="7"
        >
        <android.support.v4.view.ViewPager
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/lay_vp"
            ></android.support.v4.view.ViewPager>


    </LinearLayout>

</LinearLayout>
  • 3.在src下面,创建一个Adapter适配器的类,并继承FragmentPagerAdapter
package com.example.xiao.fragmentdemo2;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.List;



public class Adapter extends FragmentPagerAdapter{
    List <Fragment> fragmentlist;
    public Adapter(FragmentManager fm, List <Fragment> fragmentlist) {
        super(fm);
        this.fragmentlist=fragmentlist;
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentlist.get(position);
    }

    @Override
    public int getCount() {
        return fragmentlist.size();
    }
}
  • 4.最后我们在MainActivity.java中书写逻辑代码(详细看注解)
package com.example.xiao.fragmentdemo2;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private ViewPager viewPager;
    List<Fragment> fragmentList;
    Fone fragmentOne;
    Ftwo fargmentTwo;
    Fthree fragmentThree;
    TextView chars, contents, friends;
    View chars_bom, content_bom, friend_bom;

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

         //实例化fragment对象并将加到fragmentlist对象里面
        fragmentList = new ArrayList<>();
        fragmentOne = new Fone();
        fargmentTwo = new Ftwo();
        fragmentThree=new Fthree();
        fragmentList.add(fragmentOne);
        fragmentList.add(fargmentTwo);
        fragmentList.add(fragmentThree);


        chars_bom.setBackgroundColor(Color.BLUE);//给聊天文字下的view标签添加下划线

        Adapter adapter = new Adapter(getSupportFragmentManager(), fragmentList);  //实例化适配器对象,将fragmentlist传入
        viewPager.setAdapter(adapter);  //将适配器对象设置到viewPager

        //设置viewpage的监听事件
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            //滑动后产生的变化
            @Override
            public void onPageSelected(int position) {
                chars_bom.setBackgroundColor(Color.GRAY);
                content_bom.setBackgroundColor(Color.GRAY);
                friend_bom.setBackgroundColor(Color.GRAY);
                switch (position) {
                    case 0:
                        chars_bom.setBackgroundColor(Color.BLUE);
                        break;
                    case 1:
                        content_bom.setBackgroundColor(Color.BLUE);
                        break;
                    case 2:
                        friend_bom.setBackgroundColor(Color.BLUE);
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void init() {
        //初始化数据
        viewPager = findViewById(R.id.lay_vp);
        chars = findViewById(R.id.lay_charTop);
        friends = findViewById(R.id.lay_friendsTop);
        contents = findViewById(R.id.lay_contentTop);
        chars_bom = findViewById(R.id.chars_bom);
        content_bom = findViewById(R.id.content_bom);
        friend_bom = findViewById(R.id.frident_bom);
        chars.setOnClickListener(this);
        friends.setOnClickListener(this);
        contents.setOnClickListener(this);
    }


    //点击上方的按钮也会实现跳转功能
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.lay_charTop:
                viewPager.setCurrentItem(0);
                break;
            case R.id.lay_contentTop:
                viewPager.setCurrentItem(1);
                break;
            case R.id.lay_friendsTop:
                viewPager.setCurrentItem(2);
                break;
            default:
                break;
        }

    }
}

3. 探寻Fragment的生命周期

碎片主要有四种生命周期的状态
1.运动状态
2.暂停状态
3.停止状态
4.销毁状态

底层执行过程分析

添加一个碎片—->1.onAttach(当碎片和活动建立关联的时候调用)—->2.onCreate()—->3.onCreatreView(当碎片加载布局的时候调用)—->4.onActivityCreate(确保与碎片相关的活动已经创建完毕之后调用)—->5.onStart()—->6.onResume();—–>碎片激活

销毁一个碎片 当用户点击返回键或碎片被移除—–>7.onPause()—->8.onStop—->9.ondestroyView(这里可以继续往下走,也可以跳转到3,看用户怎么操作)—->10.onDestroy()—->11.onDetach()

——————————————自己的一些总结,欢迎大神指点————————————

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值