Android零基础入门第88节:Fragment显示和隐藏、绑定和解绑

    在上一期咱们学习了FragmentManager和FragmentTransaction的做用,并用案例学习了Fragment的添加、移除和替换,本期一块儿来学习Fragment显示和隐藏、绑定和解绑。java

 

 

1、Fragment显示和隐藏

 

    因为上一期有简单介绍过对应的api,这里直接经过案例来进行学习。android

    建立一个新的module名为fragmentshowhide,而后建立一个Fragment对应的布局文件fragment_demo.xml,代码以下:api

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="#f1d60d"
              android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是个人第一个Fragment"
        android:textColor="#0c1ff1"
        android:textSize="18sp"/>

</LinearLayout>

    紧接着建立一个Fragment文件,命名为DemoFragment,代码很是简单,以下:微信

package com.cqkxzsxy.jinyu.android.fragmentshowhide;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class DemoFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_demo, container, false);
        return view;
    }
}

    而后就是咱们要操做的界面设计了,这里一共包括2个按钮,分别表示隐藏Fragment和显示Fragment,主布局acticity_main文件的代码以下:架构

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/show_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="show" />

        <Button
            android:id="@+id/hide_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="hide" />

    </LinearLayout>

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

    而后就是修改主界面MainActivity的代码,获取按钮并设置监听事件,对应不一样的事件作出不一样的操做,代码以下:app

package com.cqkxzsxy.jinyu.android.fragmentshowhide;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button mHideBtn = null;
    private Button mShowBtn = null;
    private Fragment mDemoFragment = null;

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

        mHideBtn = (Button) findViewById(R.id.hide_btn);
        mShowBtn = (Button) findViewById(R.id.show_btn);

        // 建立和获取Fragment实例
        mDemoFragment = new DemoFragment();
        // 获取到FragmentManager对象
        FragmentManager fragmentManager = getFragmentManager();
        // 开启一个事务
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        // 添加Fragment
        fragmentTransaction.add(R.id.fragment_container, mDemoFragment);
        // 提交事务
        fragmentTransaction.commit();

        // 设置监听事件
        mHideBtn.setOnClickListener(this);
        mShowBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // 获取到FragmentManager对象
        FragmentManager fragmentManager = getFragmentManager();
        // 开启一个事务
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        // Fragment操做
        switch (v.getId()) {
            case R.id.hide_btn:
                if (!mDemoFragment.isHidden()) {
                    fragmentTransaction.hide(mDemoFragment);
                }
                break;
            case R.id.show_btn:
                if (mDemoFragment.isHidden()) {
                    fragmentTransaction.show(mDemoFragment);
                }
                break;
            default:
                break;
        }

        // 提交事务
        fragmentTransaction.commit();
    }
}

    运行程序,能够看到下图左侧所示界面。ide

    点击“HIDE”按钮,可将显示出来的Fragment进行隐藏,如上图右侧所示。而后再点击“SHOW”按钮,便可将刚才隐藏的Fragment从新显示出来。布局

    到这里有的同窗就会有疑问了:将Fragment隐藏的时候是否将其销毁了,而后再显示的时候从新新建的?那么接下来经过Logcat来进行验证。学习

    将DemoFragment的生命周期方法补全,并每个生命周期方法中加一句Logcat代码,而后从新运行程序。能够发现,不管咱们是隐藏仍是显示Fragment,没有任何生命周期方法被调用。说明hide操做只是将Fragment变得不可见而已,其自己仍然是存在的,在具体使用的时候须要注意。优化

 

 

2、Fragment绑定和解绑

 

    这里一样是直接跳过案例来进行学习,新建一个新的module名为fragmentattachdetach,而后建立一个Fragment对应的布局文件fragment_demo.xml,代码以下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="#f1d60d"
              android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是个人第一个Fragment"
        android:textColor="#0c1ff1"
        android:textSize="18sp"/>

</LinearLayout>

    紧接着建立一个Fragment文件,命名为DemoFragment,代码很是简单,以下:

package com.cqkxzsxy.jinyu.android.fragmentshowhide;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class DemoFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_demo, container, false);
        return view;
    }
}

    而后就是咱们要操做的界面设计了,这里一共包括2个按钮,分别表示绑定Fragment和解绑Fragment,主布局acticity_main文件的代码以下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/detach_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="detach" />

        <Button
            android:id="@+id/attach_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="attach" />

    </LinearLayout>

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

    而后就是修改主界面MainActivity的代码,获取按钮并设置监听事件,对应不一样的事件作出不一样的操做,代码以下:

package com.cqkxzsxy.jinyu.android.fragmentattachdetach;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button   mDetachBtn      = null;
    private Button   mAttachBtn      = null;
    private Fragment mDemoFragment = null;

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

        mAttachBtn = (Button) findViewById(R.id.attach_btn);
        mDetachBtn = (Button) findViewById(R.id.detach_btn);

        // 建立和获取Fragment实例
        mDemoFragment = new DemoFragment();
        // 获取到FragmentManager对象
        FragmentManager fragmentManager = getFragmentManager();
        // 开启一个事务
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        // 添加Fragment
        fragmentTransaction.add(R.id.fragment_container, mDemoFragment);
        // 提交事务
        fragmentTransaction.commit();

        // 设置监听事件
        mAttachBtn.setOnClickListener(this);
        mDetachBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // 获取到FragmentManager对象
        FragmentManager fragmentManager = getFragmentManager();
        // 开启一个事务
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        // Fragment操做
        switch (v.getId()) {
            case R.id.attach_btn:
                if (mDemoFragment.isDetached()) {
                    fragmentTransaction.attach(mDemoFragment);
                }
                break;
            case R.id.detach_btn:
                if (!mDemoFragment.isDetached()) {
                    fragmentTransaction.detach(mDemoFragment);
                }
                break;
            default:
                break;
        }

        // 提交事务
        fragmentTransaction.commit();
    }
}

    运行程序,能够看到下图左侧所示界面。

    点击“DETACH”按钮,可将显示出来的Fragment进行解绑,如上图右侧所示。而后再点击“ATTACH”按钮,便可将刚才解绑的Fragment从新绑定起来。

    有的同窗又会问了,这里的操做和前面的显示隐藏效果同样,背后的原理是否也同样呢?一样将DemoFragment的生命周期方法补全,并每个生命周期方法中加一句Logcat代码,而后从新运行程序。

    点击“DETACH”按钮时,能够看到下图所示Logcat日志信息:

    而后再点击“ATTACH”按钮,获得新的Logcat日志信息,以下:

    能够发现,当咱们detach操做的时候,首先将Fragment从UI中移除,可是仍然保存在FragmentManager对象中进行维护;attach操做就是重建Fragment视图,而后附加到UI并显示出来。

    相信经过上面2个案例,应该可以很好的理解显示和隐藏、绑定和解绑之间的区别了吧。

    这里留下一个课后做业,在实际操做中,假如我不当心隐藏或解绑了Fragment,应该如何回到以前的状态呢?

 

END

    今天就先到这里,若是在学习中存在疑惑,欢迎留言,同时也欢迎加入Android零基础入门技术讨论微信群共同窗习!

   此文章版权为微信公众号分享达人秀(ShareExpert)——鑫鱻全部,若需转载请联系做者受权,特此声明!

 

往期总结回顾:

Android零基础入门第1节:Android的前世此生

Android零基础入门第2节:Android 系统架构和应用组件那些事

Android零基础入门第3节:带你一块儿来聊一聊Android开发环境

Android零基础入门第4节:正确安装和配置JDK, 高富帅养成第一招

Android零基础入门第5节:善用ADT Bundle, 轻松邂逅女神

Android零基础入门第6节:配置优化SDK Manager, 正式约会女神

Android零基础入门第7节:搞定Android模拟器,开启甜蜜之旅

Android零基础入门第8节:HelloWorld,个人第一趟旅程出发点

Android零基础入门第9节:Android应用实战,不懂代码也能够开发

Android零基础入门第10节:开发IDE大升级,终于迎来了Android Studio

Android零基础入门第11节:简单几步带你飞,运行Android Studio工程

Android零基础入门第12节:熟悉Android Studio界面,开始装逼卖萌

Android零基础入门第13节:Android Studio个性化配置,打造开发利器

Android零基础入门第14节:使用高速Genymotion,跨入火箭时代

Android零基础入门第15节:掌握Android Studio项目结构,扬帆起航

Android零基础入门第16节:Android用户界面开发概述

Android零基础入门第17节:文本框TextView

Android零基础入门第18节:输入框EditText

Android零基础入门第19节:按钮Button

Android零基础入门第20节:复选框CheckBox和单选按钮RadioButton

Android零基础入门第21节:开关组件ToggleButton和Switch

Android零基础入门第22节:图像视图ImageView

Android零基础入门第23节:图像按钮ImageButton和缩放按钮ZoomButton

Android零基础入门第24节:自定义View简单使用,打造属于你的控件

Android零基础入门第25节:简单且最经常使用的LinearLayout线性布局

Android零基础入门第26节:两种对齐方式,layout_gravity和gravity大不一样

Android零基础入门第27节:正确使用padding和margin

Android零基础入门第28节:轻松掌握RelativeLayout相对布局

Android零基础入门第29节:善用TableLayout表格布局

Android零基础入门第30节:两分钟掌握FrameLayout帧布局

Android零基础入门第31节:少用的AbsoluteLayout绝对布局

Android零基础入门第32节:新推出的GridLayout网格布局

Android零基础入门第33节:Android事件处理概述

Android零基础入门第34节:Android中基于监听的事件处理

Android零基础入门第35节:Android中基于回调的事件处理

Android零基础入门第36节:Android系统事件的处理

Android零基础入门第37节:初识ListView

Android零基础入门第38节:初识Adapter

Android零基础入门第39节:ListActivity和自定义列表项

Android零基础入门第40节:自定义ArrayAdapter

Android零基础入门第41节:使用SimpleAdapter

Android零基础入门第42节:自定义BaseAdapter

Android零基础入门第43节:ListView优化和列表首尾使用

Android零基础入门第44节:ListView数据动态更新

Android零基础入门第45节:网格视图GridView

Android零基础入门第46节:列表选项框Spinner

Android零基础入门第47节:自动完成文本框AutoCompleteTextView

Android零基础入门第48节:可折叠列表ExpandableListView

Android零基础入门第49节:AdapterViewFlipper图片轮播

Android零基础入门第50节:StackView卡片堆叠

Android零基础入门第51节:进度条ProgressBar

Android零基础入门第52节:自定义ProgressBar炫酷进度条

Android零基础入门第53节:拖动条SeekBar和星级评分条RatingBar

Android零基础入门第54节:视图切换组件ViewSwitcher

Android零基础入门第55节:ImageSwitcher和TextSwitcher

Android零基础入门第56节:翻转视图ViewFlipper

Android零基础入门第57节:DatePicker和TimePicker选择器

Android零基础入门第58节:数值选择器NumberPicker

Android零基础入门第59节:经常使用三大Clock时钟组件

Android零基础入门第60节:日历视图CalendarView和定时器Chronometer

Android零基础入门第61节:滚动视图ScrollView

Android零基础入门第62节:搜索框组件SearchView

Android零基础入门第63节:值得借鉴学习的选项卡TabHost

Android零基础入门第64节:揭开RecyclerView庐山真面目

Android零基础入门第65节:RecyclerView分割线开发技巧

Android零基础入门第66节:RecyclerView点击事件处理

Android零基础入门第67节:RecyclerView数据动态更新

Android零基础入门第68节:RecyclerView添加首尾视图

Android零基础入门第69节:ViewPager快速实现引导页

Android零基础入门第70节:ViewPager打造TabHost效果

Android零基础入门第71节:CardView简单实现卡片式布局

Android零基础入门第72节:SwipeRefreshLayout下拉刷新

Android零基础入门第73节:Activity建立和配置

Android零基础入门第74节:Activity启动和关闭

Android零基础入门第75节:Activity状态和生命周期

Android零基础入门第76节:Activity数据保存和横竖屏切换

Android零基础入门第77节:Activity任务栈和启动模式

Android零基础入门第78节:四大组件的纽带——Intent

Android零基础入门第79节:Intent 属性详解(上)

Android零基础入门第80节:Intent 属性详解(下)

Android零基础入门第81节:Activity数据传递

Android零基础入门第82节:Activity数据回传

Android零基础入门第83节:Activity间数据传递方法汇总

Android零基础入门第84节:引入Fragment原来是这么回事

Android零基础入门第85节:Fragment使用起来如此简单

Android零基础入门第86节:探究Fragment生命周期

Android零基础入门第87节:Fragment添加、删除、替换

相关文章
相关标签/搜索