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添加、刪除、替換

相關文章
相關標籤/搜索