碎片(Fragment)的基本使用
目錄
- 一、Fragment 初探
- 1、誕生的原因
- 2、定義
- 二、Fragment 的使用方式
- 1、靜態加載碎片
- 2、動態添加碎片
- 3、在碎片中模擬回傳堆疊
- 4、碎片和活動之間的互動
- 三、Fragment 的生命周期
一、Fragment 初探
1、誕生的原因
因為螢屏大小差距過大,一些界面在手機上看起來非常美觀,但在平板上看起來可能會有控制元件被過分拉長、元素之間空隙過大等情況,為了讓界面在平板更好地展示,Android 自3.0版本開始引入了碎片的概念,

2、定義
那碎片是什么呢?碎片是一種可以嵌入在Activity當中的UI片段,碎片和Activity很像,同樣都能包含布局,同樣都有自己的生命周期,
注意:
1、Fragment不能獨立存在,必須嵌入到Activity中
2、Fragment具有自己的生命周期,接收它自己的事件,并可以在Activity運行時被添加或洗掉
3、Fragment的生命周期直接受所在的Activity的影響,如:當Activity暫停時,它擁有的所有Fragment都暫停
二、Fragment 的使用方式
我們先新建一個專案,名為 FragmentTest ,然后一起來學習一下如何使用碎片吧!(雖然碎片起初是為了兼容平板而存在,但是在手機上也應用很廣泛,所以在這里我還是使用了手機模擬器,感興趣的同學也可以用平板模擬器,碎片的使用方法也是一樣的,可參考《第一行代碼》)
1、靜態加載碎片
我們先在Activity的布局檔案 activity_main.xml 里寫一個簡單的Button控制元件
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button"
android:textSize="15sp" />
接著我們新建一個碎片布局 first_fragment.xml ,并放置了一個 TextView 用于顯示文本,為了等會更好地看到效果,我們將這個布局的背景色設定成別的顏色(我這里是水色)
<?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="#00FFFF"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is the first fragment"
android:textSize="25sp" />
</LinearLayout>
接著我們新建一個 FirstFragment 類,并讓它繼承 Fragment ,此時會有兩個不同包下的 Fragment 讓我們選擇

一個是AndroidX庫中的androidx.fragment.app.Fragment ,一個是系統內置的android.app.Fragment ,這里我們選擇AndroidX庫中的Fragment ,因為它可以讓Fragment的特性在所有Android系統版本中保持一致,而系統內置的Fragment在Android 9.0版本中已被廢棄,
然后我們重寫onCreateView()方法,在這個方法里通過LayoutInflater的inflate()方法將剛剛定義的first_fragment布局加載進來
public class FirstFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.first_fragment, container, false);
}
}
inflate() 方法帶有三個引數:
inflater:想要擴展的布局的資源 ID
container:布局將插入到的父級 ViewGroup(來自 Activity 的布局)
savedInstanceState:保存的狀態,在恢復fragment時,提供上一片段實體相關資料的 Bundle
如果第三個引數為true那么回傳可能就不是View,當為false的時候回傳就是View
在這里布林值為 false,因為系統已將擴展布局插入 container,而傳遞 true值會在最終布局中創建一個多余的視圖組
接下來我們去修改 activity_main.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:orientation="vertical">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button"
android:textSize="15sp" />
<fragment
android:id="@+id/first_fragment"
android:name="com.example.fragmenttest.FirstFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
我們使用了< fragment > 標簽在布局中添加Fragment,這里還需要通android:name屬性來顯式宣告要添加的Fragment類名,注意一定要將類的包名也加上,在這里還使用了weight屬性,將剩下來的螢屏空間全部給了fragment
?? 靜態加載碎片到這里就寫好了,現在可以運行一下程式看看效果了
2、動態添加碎片
上面這個例子只是碎片的簡單用法,在真正的專案中幾乎沒有什么實際的作用,接下來我們學習厲害一點的,在程式運行時動態地添加碎片到活動當中,
我們在前面代碼的基礎上繼續完善,首先,新建一個布局檔案second_fragment.xml ,和前面的first_fragment.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="#FFFF00"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is the second fragment"
android:textSize="25sp" />
</LinearLayout>
然后新建 SecondFragment 類,和前面一樣的套路啦
public class SecondFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.second_fragment, container, false);
}
}
接下來修改 activity_main.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:orientation="vertical">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button"
android:textSize="15sp" />
<FrameLayout
android:id="@+id/fragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
可以看到,我們將fragment換成FrameLayout(幀布局),這是安卓中最簡單的一種布局,所有的控制元件默認都會擺放在布局的左上角,同一時刻只能看到最上面的控制元件,后續添加的控制元件會覆寫前一個,由于這里僅需要在布局里放入一個Fragment,不需要任何定位和嵌套,因此非常適合使用FrameLayout,
?? 重點來啦!接著我們來看看如何實作動態添加碎片的功能,完善一下java檔案
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(this);
replaceFragment(new FirstFragment()); //初始化,一開始顯示的碎片為FirstFragment
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button:
replaceFragment(new SecondFragment()); //當點擊按鈕后,動態改變碎片,此時顯示的碎片為SecondFragment
break;
default:
break;
}
}
private void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment, fragment);
transaction.commit();
}
}
我們先實體化Button,并注冊一個點擊事件,點擊button時,會呼叫replaceFragment()方法將下側碎片替換成另一個,FragmentManager能夠實作管理activity中fragment;FragmentTransaction對fragment進行添加,移除,替換,以及執行其他動作,
動態添加碎片步驟:
1、創建待添加Fragment的實體
2、呼叫getSupportFragmentManager()方法獲取FragmentManager實體
3、呼叫beginTransaction()方法開啟一個事務
4、使用replace()方法向容器內添加或替換Fragment,需要傳入容器的id和待添加的Fragment實體
5、呼叫commit()方法提交事務
?? 現在我們可以重新運行一下程式,看看效果啦!
3、在碎片中模擬回傳堆疊
換言之,就是回傳到之前的上一個碎片,
接著上面的運行結果,我們已經點擊過了按鈕,此時螢屏上顯示的是第二個碎片,若這時按下Back鍵,你會發現,咦?怎么直接退出了,我只是想回到上一個碎片,那怎么辦呢?這時我們可以使用FragmentTransaction提供的addToBackStack()方法,傳入一個用于描述回傳堆疊狀態的引數,一般傳入null即可,
private void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
現在我們再來運行一下程式看看,是不是按下Back鍵后,回傳到第一個碎片,繼續按下Back鍵,第一個碎片會消失,再次按下Back鍵后才會退出?
4、碎片和活動之間的互動
在Activity中呼叫Fragment里的方法:先得到相應Fragment的實體,再呼叫Fragment里的方法(findFragnentById()方法,專門用于從布局中獲取碎片的實體)
FirstFragment firstFragment = getSupportFragmentManager()
.findFragmentById(R.id.first_fragment);
在Fragment中呼叫Activity里的方法:呼叫getActivity() 方法來得到和當前碎片相關聯的活動實體,再呼叫Activity里的方法
MainActivity activity = getActivity();
在這里我就不舉例子詳細介紹了,想要繼續了解的同學可以自己看看相關博客或者《第一行代碼》呀!
三、Fragment 的生命周期
Fragment的生命周期和Activity的生命周期很像,在這里我就不詳細講解啦,感興趣的同學可以自己去了解一下
OK,講完啦!但這只是碎片的基礎知識,進一步的學習和應用需要你們自己去探索哦!最后,悄悄問一句,你的冬令營作品開始做了嗎??期待看到大家的作品哦?
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/357159.html
標籤:其他
