Android Fragment(動(dòng)態(tài),靜態(tài))碎片詳解及總結(jié)
Android Fragment(動(dòng)態(tài),靜態(tài))碎片詳解
一.Fragment的相關(guān)概念(一)Fragment的基礎(chǔ)知識(shí)
Fragment是Android3.0新增的概念,中文意思是碎片,它與Activity十分相似,用來(lái)在一個(gè) Activity中描述一些行為或一部分用戶界面.使用多個(gè)Fragment可以在一個(gè)單獨(dú)的Activity中建 立多個(gè)UI面板,也可以在多個(gè)Activity中使用Fragment。
Fragment擁有自己的生命 周期和接收、處理用戶的事件,這樣就不必在Activity寫一堆控件的事件處理的代碼了。更為 重要的是,你可以動(dòng)態(tài)的添加、替換和移除某個(gè)Fragment。
一個(gè)Fragment必須總是被嵌入到一個(gè)Activity中,它的生命周期直接被其所屬的宿主Activity生 命周期影響,它的狀態(tài)會(huì)隨宿主的狀態(tài)變化而變化。 要?jiǎng)?chuàng)建一個(gè)Fragment 必須創(chuàng)建一個(gè)Fragment的子類,或者繼承自另一個(gè)已經(jīng)存在的 Fragment的子類.并重寫 onCreateView()方法加載UI。
(二)Fragment生命周期
因?yàn)镕ragment必須嵌入在Acitivity中使用,所以Fragment的生命周期和它所在的Activity是 密切相關(guān)的。 如果Activity是暫停狀態(tài),其中所有的Fragment都是暫停狀態(tài);如果Activity是stopped狀 態(tài),這個(gè)Activity中所有的Fragment都不能被啟動(dòng);如果Activity被銷毀,那么它其中的所有 Fragment都會(huì)被銷毀。 但是,當(dāng)Activity在活動(dòng)狀態(tài),可以獨(dú)立控制Fragment的狀態(tài),比如加上或者移除 Fragment。 當(dāng)這樣進(jìn)行fragment transaction(轉(zhuǎn)換)的時(shí)候,可以把fragment放入Activity的back stack中,這樣用戶就可以進(jìn)行返回操作。
下面是Activity對(duì)象和Fragment對(duì)象的全部生命周期的對(duì)比圖:
可以看到Activity有七個(gè)生命周期,F(xiàn)ragment有十一個(gè)生命周期。
(三)Fragment中幾個(gè)重要的回調(diào)方法說(shuō)明:1.onAttach(Activity)
當(dāng)Fragment與Activity發(fā)生關(guān)聯(lián)時(shí)調(diào)用。
2.onCreateView(LayoutInflater, ViewGroup,Bundle) 創(chuàng)建該Fragment的視圖3.onActivityCreated(Bundle)
當(dāng)Activity的onCreate方法返回時(shí)調(diào)用
4.onDestoryView()
與onCreateView相對(duì)應(yīng),當(dāng)該Fragment的視圖被移除時(shí)調(diào)用
5.onDetach()與onAttach相對(duì)應(yīng)
當(dāng)Fragment與Activity關(guān)聯(lián)被取消時(shí)調(diào)用
注意:除了onCreateView,其他的所有方法如果你重寫了,必須調(diào)用父類對(duì)于該方法的實(shí)現(xiàn),就是Super。。不能去掉。
(四)Fragment家族常用的API1.
Fragment常用的三個(gè)類:
(1)android.app.Fragment主要用于定義
(2)Fragment android.app.FragmentManager 主要用于在Activity中操作
(3)Fragment android.app.FragmentTransaction 保證一些列Fragment操作的原子性,熟悉事務(wù)這個(gè)詞, 一定能明白。
2.獲取FragmentManage的方式:
(1)getFragmentManager()
(2)getSupportFragmentManager //v4包中FragmentActivity
3.FragmentTransaction的操作和方法(1)開啟一個(gè)事務(wù)
FragmentTransaction transaction = fm.benginTransatcion();
(2)往Activity中添加一個(gè)Fragment
transaction.add()
(3)從Activity中移除一個(gè)Fragment,如果被移除的Fragment沒(méi)有添加到回退棧(回退棧后面會(huì)詳細(xì)說(shuō)),這個(gè)Fragment實(shí)例將會(huì)被銷毀。
transaction.remove()
(4)使用另一個(gè)Fragment替換當(dāng)前的,實(shí)際上就是remove()然后add()的合體
transaction.replace()
(5)當(dāng)你的fragment數(shù)量固定很少時(shí)隱藏當(dāng)前的Fragment,僅僅是設(shè)為不可見(jiàn),并不會(huì)銷毀,多的時(shí)候可能出現(xiàn)OOM異常
transaction.hide()
(6)顯示之前隱藏的Fragment
transaction.show()
(7)detach()會(huì)將view從UI中移除,和remove()不同,此時(shí)fragment的狀態(tài)依然由FragmentMa nager維護(hù)。(8)attach()重建view視圖,附加到UI上并顯示。(9)transatcion.commit()//提交一個(gè)事務(wù)
上述,基本是操作Fragment的所有的方式了,在一個(gè)事務(wù)開啟到提交可以進(jìn)行多個(gè)的添加、 移除、替換等操作。
值得注意的是:如果你喜歡使用Fragment,一定要清楚這些方法,哪個(gè)會(huì)銷毀視圖,哪個(gè)會(huì)銷毀實(shí)例,哪個(gè)僅僅只是隱藏,這樣才能更好的使用它們。
比如:我在FragmentA中的EditText填了一些數(shù)據(jù),當(dāng)切換到FragmentB時(shí),如果希望回到A還能看到數(shù)據(jù),則適合你的就是hide和show;也就是說(shuō),希望保留用戶操作的面板,你可以使用hide和show,當(dāng)然了不要使勁在那new實(shí)例,最好進(jìn)行下非null判斷。
再比如:我不希望保留用戶操作,你可以使用remove(),然后add();或者使用replace() 這個(gè)和remove,add是相同的效果。
remove和detach有一點(diǎn)細(xì)微的區(qū)別,在不考慮回退棧的情況下,remove會(huì)銷毀整個(gè) Fragment實(shí)例,而detach則只是銷毀其視圖結(jié)構(gòu),實(shí)例并不會(huì)被銷毀。那么二者怎么取舍使用呢?如果你的當(dāng)前Activity一直存在,那么在不希望保留用戶操作的時(shí)候,你可以優(yōu)先使用 detach。
二.Activity中添加Fragment
(一)添加Fragment的兩種方法1.方法一(Activity的布局文件中加入標(biāo)簽) 在XML中配置更加簡(jiǎn)單一點(diǎn),但是靈活性不夠,不能在同一個(gè)位置去切換多個(gè)不同的 Fragment
<fragment android:id="@+id/myfragment" android:name="包名.Fragment類名" android:layout_width="match_parent" android:layout_height="match_parent" />
注意:fragment必須設(shè)置id或者tag,并且需要指定name為類名。
這樣使用就相當(dāng)于把fragment當(dāng)作一塊布局來(lái)使用了!
2.方法二(使用FragmentTransaction的add()方法加入fragment)(1)獲取到FragmentManager,在Activity中可以直接通過(guò)getFragmentManager得到。
FragmentManager fragmentManager = getFragmentManager();//這里要注意是否是V4包的
(2)開啟一個(gè)事務(wù),通過(guò)調(diào)用beginTransaction方法開啟。
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
(3)向容器內(nèi)加入Fragment,一般使用add或者replace方法實(shí)現(xiàn),需要傳入容器的id和 Fragment的實(shí)例。
fragmentTransaction.replace(Activity設(shè)置的布局中的ViewGroup組件id,需要替換的Fragment實(shí)例);
//也可以使用三參的方法,傳遞一個(gè)Tag
(4)提交事務(wù),調(diào)用commit方法提交。
fragmentTransaction.commit();
(二)Fragment回退棧
類似與Android系統(tǒng)為Activity維護(hù)一個(gè)任務(wù)棧,我們也可以通過(guò)Activity維護(hù)一個(gè)回退棧來(lái)保 存每次Fragment事務(wù)發(fā)生的變化。如果你將Fragment任務(wù)添加到回退棧,當(dāng)用戶點(diǎn)擊后退按鈕時(shí),將看到上一次的保存的Fragment。一旦Fragment完全從后退棧中彈出,用戶再次點(diǎn)擊后退鍵,則退出當(dāng)前Activity。 假設(shè)現(xiàn)在我們有兩個(gè)Fragment:Fragment01和Fragment02,我們現(xiàn)在從Fragment01的界面跳到Fragment02,然后按Back鍵,發(fā)現(xiàn)程序是直接退出了,而不是返回到Fragment01。 如果現(xiàn)在想實(shí)現(xiàn)以下功能:從Fragment01的界面跳到Fragment02,然后按Back鍵,會(huì)返回到Fragment01,就需要加入回退棧了,F(xiàn)ragmentTransaction中提供了一個(gè) addToBackStack()方法,可以將一個(gè)事務(wù)添加到返回棧中。
1. transaction.add(R.id.right, rightFragment);
2. transaction.addToBackStack(null);
我們?cè)谑聞?wù)提交之前調(diào)用了FragmentTransaction的addToBackStack()方法,它可以接受一個(gè)名字用于描述返回棧的狀態(tài),一般傳入null即可。
下面是Fragment程序的示例
三.靜態(tài)顯示Fragment碎片頁(yè)面,并進(jìn)行兩碎片頁(yè)面的數(shù)據(jù)通信
這里左邊四個(gè)按鈕是一個(gè)碎片布局,右邊的碎片布局是一個(gè)ListView顯示數(shù)據(jù)。
程序運(yùn)行后效果:
數(shù)據(jù)交換的后的情況:
設(shè)計(jì)代碼:
布局文件比較簡(jiǎn)單,所以先展示布局文件。再展示java代碼設(shè)計(jì)。
(一)布局文件activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <fragment android:id="@+id/main_frag1" android:name="com.example.xmlfragment.FragmentA" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> <fragment android:id="@+id/main_frag2" android:name="com.example.xmlfragment.FragmentB" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> </LinearLayout>
這里設(shè)計(jì)兩個(gè)靜態(tài)的碎片文件,使用的是小寫的fragment標(biāo)簽,里面必須要有name和id(或tag)屬性。
(二)第一個(gè)碎片頁(yè)面包含的布局文件fragment_a.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/music" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="音樂(lè)" /> <Button android:id="@+id/sports" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="體育" /> <Button android:id="@+id/arts" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="美術(shù)" /> <Button android:id="@+id/dance" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="舞蹈" /> </LinearLayout>
(三)第二個(gè)碎片頁(yè)面包含的布局文件fragment_b.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"> <ListView android:id="@+id/frag2_lv" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
(四)第一個(gè)碎片頁(yè)面的java代碼設(shè)計(jì):
package com.example.xmlfragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; /** * 碎片頁(yè)面A的顯示,這里顯示四個(gè)按鈕 */ public class FragmentA extends Fragment implements View.OnClickListener { //布局中的控件 Button music; Button sports; Button arts; Button dance; /** * onCreate執(zhí)行之后執(zhí)行的方法,一般用于顯示視圖 */ @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { //不要super實(shí)現(xiàn)的方法,它是返回空值的 return View.inflate(getActivity(), R.layout.fragment_a, null); } //這個(gè)方法不在Fragment的生命周期里面 //但是它會(huì)在onCreateView后面執(zhí)行,里面的參數(shù)View就是上面?zhèn)魅氲膙iew對(duì)象 @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); //實(shí)例化布局上的控件 music = (Button) view.findViewById(R.id.music); sports = (Button) view.findViewById(R.id.sports); arts = (Button) view.findViewById(R.id.arts); dance = (Button) view.findViewById(R.id.dance); //給控件添加監(jiān)聽(tīng)事件 music.setOnClickListener(this); sports.setOnClickListener(this); arts.setOnClickListener(this); dance.setOnClickListener(this); } //實(shí)現(xiàn)監(jiān)聽(tīng)的方法 @Override public void onClick(View v) { //獲取頁(yè)面碎片B的對(duì)象,來(lái)對(duì)頁(yè)面碎片B進(jìn)行操作,這里不能使用new的方法來(lái)創(chuàng)建對(duì)象 FragmentB fragmentB = (FragmentB) getActivity().getSupportFragmentManager().findFragmentById(R.id.main_frag2); switch (v.getId()) { case R.id.music: fragmentB.list.add(0, "音樂(lè)");//給頁(yè)面B的集合中添加數(shù)據(jù) Toast.makeText(getActivity(), "music", Toast.LENGTH_SHORT).show(); break; case R.id.sports: fragmentB.list.add(0, "運(yùn)動(dòng)");//給頁(yè)面B的集合中添加數(shù)據(jù) Toast.makeText(getActivity(), "sports", Toast.LENGTH_SHORT).show(); break; case R.id.arts: fragmentB.list.add(0, "藝術(shù)");//給頁(yè)面B的集合中添加數(shù)據(jù) Toast.makeText(getActivity(), "arts", Toast.LENGTH_SHORT).show(); break; case R.id.dance: fragmentB.list.add(0, "跳舞");//給頁(yè)面B的集合中添加數(shù)據(jù) Toast.makeText(getActivity(), "dance", Toast.LENGTH_SHORT).show(); break; } fragmentB.adapter.notifyDataSetChanged();//刷新頁(yè)面B的數(shù)據(jù) } }
(五)第二個(gè)碎片頁(yè)面的java代碼設(shè)計(jì)
package com.example.xmlfragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.List; /** * 碎片頁(yè)面B的顯示,這里顯示一個(gè)ListView數(shù)據(jù) */ public class FragmentB extends Fragment implements AdapterView.OnItemClickListener { //定義集合、適配器、ListView List<String> list; ArrayAdapter<String> adapter; ListView listView; //數(shù)據(jù)源的其中一個(gè)字符串變量 String name = "music"; /** * 最先執(zhí)行,一般是處理于界面無(wú)關(guān)的數(shù)據(jù) */ @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //實(shí)例化list集合 list = new ArrayList<>(); //實(shí)例化ListView //添加數(shù)據(jù)源 for (int i = 1; i <= 100; i++) { list.add(name + i); } //實(shí)例化Adapter對(duì)象 adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_activated_1, list); } /** * onCreate執(zhí)行之后執(zhí)行的方法,一般用于顯示視圖 */ @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { //不要super實(shí)現(xiàn)的方法,它是返回空值的 return View.inflate(getActivity(), R.layout.fragment_b, null); } /*** * fragment創(chuàng)建前最后執(zhí)行的方法 * 加載視圖上面顯示的數(shù)據(jù)和默認(rèn)設(shè)置 */ @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); //這里的View上面加載的ListView listView = (ListView) view.findViewById(R.id.frag2_lv); //給ListView添加適配器 listView.setAdapter(adapter); //給ListView添加點(diǎn)擊的監(jiān)聽(tīng)事件 listView.setOnItemClickListener(this); //獲取碎片A的對(duì)象 fragmentA= (FragmentA) getActivity().getSupportFragmentManager().findFragmentById(R.id.main_frag1); } /** * ListView中點(diǎn)擊對(duì)應(yīng)的條目的回調(diào)方法 */ FragmentA fragmentA; @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //這里修改頁(yè)面A中的第一個(gè)按鈕的文本 //點(diǎn)擊ListView哪個(gè)條目,這個(gè)條目的文本都會(huì)顯示在第一個(gè)按鈕上(實(shí)現(xiàn)Fragment之間的通信) fragmentA.music.setText(list.get(position)); } }
(六)主方法類的java代碼:
package com.example.xmlfragment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
可以看到主方法類里面什么都不用設(shè)計(jì),只需要把布局顯示出來(lái)就可以了,這里全部的處理都是在fragment碎片中做好了,這就是碎片的好處。
四.動(dòng)態(tài)創(chuàng)建碎片的示例
程序運(yùn)行后的界面:
點(diǎn)擊某個(gè)按鈕,選擇顯示對(duì)應(yīng)的碎片頁(yè)面
代碼設(shè)計(jì):
(一)布局文件設(shè)計(jì)activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.fragment.MainActivity"> <RadioGroup android:background="@drawable/tab_bg" android:id="@+id/main_rg" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:orientation="horizontal"> <RadioButton android:id="@+id/main_rb1" style="@style/buttonstyle" android:drawableTop="@drawable/contact" android:textColor="@color/mytextcolors" android:text="聯(lián)系人" /> <RadioButton android:id="@+id/main_rb2" style="@style/buttonstyle" android:drawableTop="@drawable/message" android:textColor="@color/mytextcolors" android:text="消息" /> <RadioButton android:id="@+id/main_rb3" style="@style/buttonstyle" android:drawableTop="@drawable/news" android:textColor="@color/mytextcolors" android:text="動(dòng)態(tài)" /> <RadioButton android:id="@+id/main_rb4" style="@style/buttonstyle" android:drawableTop="@drawable/setting" android:textColor="@color/mytextcolors" android:text="設(shè)置" /> </RadioGroup> <FrameLayout android:id="@+id/main_fl" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/main_rg"/> </RelativeLayout>
這里動(dòng)態(tài)顯示的碎片頁(yè)面在先設(shè)置一個(gè)FrameLayout布局容器來(lái)存放碎片頁(yè)面。
下面簡(jiǎn)單設(shè)計(jì)碎片頁(yè)面。
(二)聯(lián)系人頁(yè)面碎片
package com.example.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** *這是聯(lián)系人碎片頁(yè)面 */ public class ContactFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { TextView textView = new TextView(getActivity()); textView.setText("這是聯(lián)系人頁(yè)面"); textView.setTextSize(30); return textView; } }
(三)消息頁(yè)面碎片
package com.example.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * 這是消息頁(yè)面的碎片 */ public class MessageFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { TextView textView = new TextView(getActivity()); textView.setText("這是消息頁(yè)面"); textView.setTextSize(30); return textView; } }
(四)動(dòng)態(tài)頁(yè)面碎片
package com.example.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** *這是動(dòng)態(tài)頁(yè)面的碎片 */ public class NewsFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { TextView textView = new TextView(getActivity()); textView.setText("這是動(dòng)態(tài)頁(yè)面"); textView.setTextSize(30); return textView; } }
(五)動(dòng)態(tài)頁(yè)面碎片
package com.example.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** *這是動(dòng)態(tài)頁(yè)面的碎片 */ public class NewsFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { TextView textView = new TextView(getActivity()); textView.setText("這是動(dòng)態(tài)頁(yè)面"); textView.setTextSize(30); return textView; } }
上面就是四個(gè)碎片頁(yè)面的設(shè)計(jì),都是比較簡(jiǎn)單的頁(yè)面設(shè)計(jì),其實(shí)也是可以像Activity一樣設(shè)計(jì)成一個(gè)很復(fù)雜頁(yè)面的顯示。
(六)主方法類,重點(diǎn)理解
package com.example.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.widget.FrameLayout; import android.widget.RadioGroup; public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener { //定義布局內(nèi)的控件 RadioGroup radioGroup; FrameLayout frameLayout; //定義四個(gè)存放碎片的數(shù)組 Fragment[] fragment = new Fragment[4]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); radioGroup.check(R.id.main_rb1); //顯示第一個(gè)碎片頁(yè)面 showFragment(0); } /** * 顯示碎片頁(yè)面的方法 * 這里是要重點(diǎn)理解的地方 * 這里要添加和移除的操作都有,而且還有進(jìn)行一定的判斷 */ //定義一個(gè)當(dāng)前點(diǎn)擊的游標(biāo)值,默認(rèn)是-1,說(shuō)明還沒(méi)有點(diǎn) int currentIndex = -1; private void showFragment(int i) { //如果點(diǎn)擊的頁(yè)面是剛才顯示的頁(yè)面,就什么都不做 if (i == currentIndex) { return; } //處理碎片,顯示、移除等等 //這里要用碎片的事務(wù)來(lái)完成 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); //如果用戶打開已經(jīng)打開過(guò)一個(gè)Fragment頁(yè)面,再打開其他頁(yè)面后,要先把原來(lái)的頁(yè)面移除 if (currentIndex != -1) { //移除碎片 transaction.hide(fragment[currentIndex]); } //顯示新的碎片 if (fragment[i] == null) { //創(chuàng)建碎片 CreateFragment(i); //使用事務(wù)顯示碎片 //第一個(gè)參數(shù)是碎片要顯示的布局的位置的ID號(hào) //第二個(gè)參數(shù)是顯示的碎片的對(duì)象 transaction.add(R.id.main_fl, fragment[i]); } else { //如果碎片曾經(jīng)顯示過(guò)就顯示出來(lái)就可以了 transaction.show(fragment[i]); // transaction.addToBackStack(null); } //保存用戶點(diǎn)擊的游標(biāo)值 currentIndex = i; //最后提交事務(wù),把碎片放置到位 transaction.commit(); } //初始化數(shù)據(jù) private void initView() { //實(shí)例化數(shù)據(jù) radioGroup = (RadioGroup) findViewById(R.id.main_rg); frameLayout = (FrameLayout) findViewById(R.id.main_fl); //給GroupButton設(shè)置監(jiān)聽(tīng)事件 radioGroup.setOnCheckedChangeListener(this); } /** * 按鈕選擇后觸發(fā)的方法 */ @Override public void onCheckedChanged(RadioGroup group, int checkedId) { //點(diǎn)擊哪一個(gè)按鈕就顯示哪一個(gè)碎片 //這里的checkedID不是0、1、2、3這種數(shù)值,而是布局里面對(duì)應(yīng)的控件的ID值 switch (checkedId) { case R.id.main_rb1: showFragment(0); break; case R.id.main_rb2: showFragment(1); break; case R.id.main_rb3: showFragment(2); break; case R.id.main_rb4: showFragment(3); break; } } /** * 創(chuàng)建碎片頁(yè)面對(duì)象的方法 */ private void CreateFragment(int i) { //如果碎片是第一次點(diǎn)開,就要?jiǎng)?chuàng)建碎片 switch (i) { case 0: fragment[i] = new ContactFragment(); break; case 1: fragment[i] = new MessageFragment(); break; case 2: fragment[i] = new NewsFragment(); break; case 3: fragment[i] = new SettingFragment(); break; } } }
程序運(yùn)行后就可以顯示界面了。這就是動(dòng)態(tài)創(chuàng)建碎片的示例。
五.動(dòng)態(tài)創(chuàng)建碎片和靜態(tài)創(chuàng)建碎片的對(duì)比:
很多人都會(huì)有疑問(wèn):動(dòng)態(tài)創(chuàng)建和靜態(tài)創(chuàng)建碎片有什么區(qū)別?
其實(shí)主要是應(yīng)用場(chǎng)合的區(qū)別,并且我們也要知道它們的創(chuàng)建的區(qū)別。
(一)碎片靜態(tài)創(chuàng)建和動(dòng)態(tài)創(chuàng)建的區(qū)別1.靜態(tài)創(chuàng)建碎片
在布局內(nèi)創(chuàng)建fragment標(biāo)簽,并且標(biāo)簽內(nèi)有屬性:name和id(或tag),其中id或tag是一個(gè)唯一標(biāo)識(shí),是用來(lái)找到這個(gè)碎片對(duì)象用的;而name是繼承了Fragment的自定義類,使用包名+類名設(shè)置。
靜態(tài)創(chuàng)建的碎片一旦創(chuàng)建它就在這個(gè)Activity頁(yè)面的固定位置了。
2.動(dòng)態(tài)創(chuàng)建碎片
要在布局文件內(nèi)先創(chuàng)建層布局容器標(biāo)簽FrameLayout,動(dòng)態(tài)創(chuàng)建的碎片頁(yè)面都是顯示在這個(gè)容器里面的。這里控制碎片改變是在所依賴的Activity頁(yè)面的代碼當(dāng)中來(lái)控制。都是通過(guò)事務(wù)來(lái)顯示或隱藏碎片,達(dá)到碎片切換的效果。
(二)靜態(tài)碎片和動(dòng)態(tài)碎片的應(yīng)用場(chǎng)合1.靜態(tài)碎片的應(yīng)用場(chǎng)合
靜態(tài)碎片的應(yīng)用場(chǎng)合是多個(gè)頁(yè)面都會(huì)出現(xiàn)這種布局,并且它的事件處理是一樣的。
比如下面兩個(gè)頁(yè)面:
上面兩不同的頁(yè)面中,最下方的顯示都是一樣的,并且點(diǎn)擊某個(gè)按鈕跳轉(zhuǎn)到的頁(yè)面都是一樣的,這時(shí)就需要用靜態(tài)的碎片。
使用方法:只要把這個(gè)靜態(tài)標(biāo)簽的fragment放到這兩頁(yè)面的底部就可以了。
對(duì)于上面兩個(gè)頁(yè)面但是如果你不用使用碎片,就需要在兩個(gè)頁(yè)面都設(shè)置這幾個(gè)控件,并且它們的點(diǎn)擊事件的處理,都要在兩個(gè)頁(yè)面的Activity中重新做。這就降低了代碼的復(fù)用性。
靜態(tài)碎片是固定的,但是它的事件處理都是已經(jīng)寫好了的,都在自定義的Fragment類中,你使用的使用只要復(fù)制靜態(tài)的xml代碼就可以了。
在開發(fā)中,如果是多個(gè)頁(yè)面有相同的一些小布局,這時(shí)使用靜態(tài)碎片就非常必要了。
2.動(dòng)態(tài)碎片的應(yīng)用場(chǎng)合
動(dòng)態(tài)碎片的應(yīng)用場(chǎng)合應(yīng)該是比較容易就看出來(lái)的,就是某一個(gè)頁(yè)面,通過(guò)幾個(gè)按鈕實(shí)現(xiàn)頁(yè)面中局部畫面的切換。
最常見(jiàn)的應(yīng)用場(chǎng)合:
這里在同一個(gè)Activity中可以顯示多個(gè)頁(yè)面,并且頁(yè)面之間可以實(shí)現(xiàn)簡(jiǎn)單的切換,這就是動(dòng)態(tài)創(chuàng)建碎片的應(yīng)用。
在實(shí)際開發(fā)中,上面的頁(yè)面還要實(shí)現(xiàn)左右滑動(dòng)來(lái)切換頁(yè)面,這就需要ViewPager,使用ViewPager能非常方便的實(shí)現(xiàn)頁(yè)面的切換,并且不需要事務(wù)處理。這個(gè)知識(shí)點(diǎn)后面總結(jié)。
最后簡(jiǎn)單說(shuō)一下:
其實(shí)碎片就像一個(gè)Activity,它也是可以顯示很多頁(yè)面數(shù)據(jù),并且可以實(shí)現(xiàn)頁(yè)面的跳轉(zhuǎn),數(shù)據(jù)的傳遞。但是它是不用在AndroidManifest中注冊(cè)的。
碎片頁(yè)面的跳轉(zhuǎn)到其他Activity頁(yè)面也是使用startActivity或StartActivityForResult。
數(shù)據(jù)傳遞也是可以通過(guò)Intent來(lái)攜帶數(shù)據(jù)。
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
Android開發(fā)中的重力傳感器用法實(shí)例詳解
這篇文章主要介紹了Android開發(fā)中的重力傳感器用法,簡(jiǎn)單分析了Android重力傳感器的基本功能、使用方法,并結(jié)合實(shí)例形式分析了Android基于重力傳感器實(shí)現(xiàn)橫豎屏切換的相關(guān)操作技巧,需要的朋友可以參考下2017-11-11Android開發(fā)實(shí)現(xiàn)自定義新聞加載頁(yè)面功能實(shí)例
這篇文章主要介紹了Android開發(fā)實(shí)現(xiàn)自定義新聞加載頁(yè)面功能,結(jié)合具體實(shí)例形式分析了Android界面加載及頁(yè)面布局相關(guān)操作技巧,需要的朋友可以參考下2017-10-10Android Textview實(shí)現(xiàn)顏色漸變滾動(dòng)效果
這篇文章主要為大家詳細(xì)介紹了Android Textview實(shí)現(xiàn)顏色漸變滾動(dòng)效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10五分鐘教你Android-Kotlin項(xiàng)目編寫
本篇文章主要介紹了五分鐘教你Android-Kotlin項(xiàng)目編寫,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-06-06Android TextView實(shí)現(xiàn)跑馬燈效果的方法
這篇文章主要介紹了Android TextView跑馬燈效果實(shí)現(xiàn)方法,涉及Android布局文件中相關(guān)屬性的設(shè)置技巧,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-01-01Android APP開發(fā)KML軌跡導(dǎo)出教程示例
這篇文章主要為大家介紹了Android APP開發(fā)KML軌跡導(dǎo)出教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12Android將Xamarin For VS升級(jí)為4.1.0.530版教程
這篇文章主要介紹了Android將Xamarin For VS升級(jí)為4.1.0.530版的圖文教程,感興趣的小伙伴們可以參考一下2016-06-06Android 滾動(dòng)時(shí)間選擇的示例代碼
這篇文章主要介紹了Android 滾動(dòng)時(shí)間選擇的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12Android應(yīng)用中使用ViewPager和ViewPager指示器來(lái)制作Tab標(biāo)簽
這篇文章主要介紹了Android中使用ViewPager和ViewPager指示器來(lái)制作Tab標(biāo)簽的方法,ViewPager指示器ViewPageIndicator是一個(gè)開源庫(kù),文中舉了一個(gè)仿網(wǎng)易新聞客戶端Tab標(biāo)簽的例子,需要的朋友可以參考下2016-03-03