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

来源:互联网 发布:网络语言排面什么意思 编辑:程序博客网 时间:2024/04/30 17:49

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

一、Fragment显示和隐藏

    由于上一期有简单介绍过对应的api,这里直接通过案例来进行学习。

    创建一个新的module名为fragmentshowhide,然后创建一个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/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的代码,获取按钮并设置监听事件,对应不同的事件做出不同的操作,代码如下:

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();    }}

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

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

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

    将DemoFragment的生命周期方法补全,并每一个生命周期方法中加一句Logcat代码,然后重新运行程序。可以发现,无论我们是隐藏还是显示Fragment,没有任何生命周期方法被调用。说明hide操作只是将Fragment变得不可见而已,其本身仍然是存在的,在具体使用的时候需要注意。

二、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添加、删除、替换

阅读全文
0 0