Android Fragment(動態(tài),靜態(tài))碎片詳解及總結(jié)
Android Fragment(動態(tài),靜態(tài))碎片詳解
一.Fragment的相關(guān)概念(一)Fragment的基礎(chǔ)知識
Fragment是Android3.0新增的概念,中文意思是碎片,它與Activity十分相似,用來在一個 Activity中描述一些行為或一部分用戶界面.使用多個Fragment可以在一個單獨的Activity中建 立多個UI面板,也可以在多個Activity中使用Fragment。
Fragment擁有自己的生命 周期和接收、處理用戶的事件,這樣就不必在Activity寫一堆控件的事件處理的代碼了。更為 重要的是,你可以動態(tài)的添加、替換和移除某個Fragment。
一個Fragment必須總是被嵌入到一個Activity中,它的生命周期直接被其所屬的宿主Activity生 命周期影響,它的狀態(tài)會隨宿主的狀態(tài)變化而變化。 要創(chuàng)建一個Fragment 必須創(chuàng)建一個Fragment的子類,或者繼承自另一個已經(jīng)存在的 Fragment的子類.并重寫 onCreateView()方法加載UI。
(二)Fragment生命周期
因為Fragment必須嵌入在Acitivity中使用,所以Fragment的生命周期和它所在的Activity是 密切相關(guān)的。 如果Activity是暫停狀態(tài),其中所有的Fragment都是暫停狀態(tài);如果Activity是stopped狀 態(tài),這個Activity中所有的Fragment都不能被啟動;如果Activity被銷毀,那么它其中的所有 Fragment都會被銷毀。 但是,當(dāng)Activity在活動狀態(tài),可以獨立控制Fragment的狀態(tài),比如加上或者移除 Fragment。 當(dāng)這樣進行fragment transaction(轉(zhuǎn)換)的時候,可以把fragment放入Activity的back stack中,這樣用戶就可以進行返回操作。
下面是Activity對象和Fragment對象的全部生命周期的對比圖:

可以看到Activity有七個生命周期,F(xiàn)ragment有十一個生命周期。
(三)Fragment中幾個重要的回調(diào)方法說明:1.onAttach(Activity)
當(dāng)Fragment與Activity發(fā)生關(guān)聯(lián)時調(diào)用。
2.onCreateView(LayoutInflater, ViewGroup,Bundle) 創(chuàng)建該Fragment的視圖3.onActivityCreated(Bundle)
當(dāng)Activity的onCreate方法返回時調(diào)用
4.onDestoryView()
與onCreateView相對應(yīng),當(dāng)該Fragment的視圖被移除時調(diào)用
5.onDetach()與onAttach相對應(yīng)
當(dāng)Fragment與Activity關(guān)聯(lián)被取消時調(diào)用
注意:除了onCreateView,其他的所有方法如果你重寫了,必須調(diào)用父類對于該方法的實現(xiàn),就是Super。。不能去掉。
(四)Fragment家族常用的API1.
Fragment常用的三個類:
(1)android.app.Fragment主要用于定義
(2)Fragment android.app.FragmentManager 主要用于在Activity中操作
(3)Fragment android.app.FragmentTransaction 保證一些列Fragment操作的原子性,熟悉事務(wù)這個詞, 一定能明白。
2.獲取FragmentManage的方式:
(1)getFragmentManager()
(2)getSupportFragmentManager //v4包中FragmentActivity
3.FragmentTransaction的操作和方法(1)開啟一個事務(wù)
FragmentTransaction transaction = fm.benginTransatcion();
(2)往Activity中添加一個Fragment
transaction.add()
(3)從Activity中移除一個Fragment,如果被移除的Fragment沒有添加到回退棧(回退棧后面會詳細說),這個Fragment實例將會被銷毀。
transaction.remove()
(4)使用另一個Fragment替換當(dāng)前的,實際上就是remove()然后add()的合體
transaction.replace()
(5)當(dāng)你的fragment數(shù)量固定很少時隱藏當(dāng)前的Fragment,僅僅是設(shè)為不可見,并不會銷毀,多的時候可能出現(xiàn)OOM異常
transaction.hide()
(6)顯示之前隱藏的Fragment
transaction.show()
(7)detach()會將view從UI中移除,和remove()不同,此時fragment的狀態(tài)依然由FragmentMa nager維護。(8)attach()重建view視圖,附加到UI上并顯示。(9)transatcion.commit()//提交一個事務(wù)
上述,基本是操作Fragment的所有的方式了,在一個事務(wù)開啟到提交可以進行多個的添加、 移除、替換等操作。
值得注意的是:如果你喜歡使用Fragment,一定要清楚這些方法,哪個會銷毀視圖,哪個會銷毀實例,哪個僅僅只是隱藏,這樣才能更好的使用它們。
比如:我在FragmentA中的EditText填了一些數(shù)據(jù),當(dāng)切換到FragmentB時,如果希望回到A還能看到數(shù)據(jù),則適合你的就是hide和show;也就是說,希望保留用戶操作的面板,你可以使用hide和show,當(dāng)然了不要使勁在那new實例,最好進行下非null判斷。
再比如:我不希望保留用戶操作,你可以使用remove(),然后add();或者使用replace() 這個和remove,add是相同的效果。
remove和detach有一點細微的區(qū)別,在不考慮回退棧的情況下,remove會銷毀整個 Fragment實例,而detach則只是銷毀其視圖結(jié)構(gòu),實例并不會被銷毀。那么二者怎么取舍使用呢?如果你的當(dāng)前Activity一直存在,那么在不希望保留用戶操作的時候,你可以優(yōu)先使用 detach。
二.Activity中添加Fragment
(一)添加Fragment的兩種方法1.方法一(Activity的布局文件中加入標(biāo)簽) 在XML中配置更加簡單一點,但是靈活性不夠,不能在同一個位置去切換多個不同的 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)作一塊布局來使用了!
2.方法二(使用FragmentTransaction的add()方法加入fragment)(1)獲取到FragmentManager,在Activity中可以直接通過getFragmentManager得到。
FragmentManager fragmentManager = getFragmentManager();//這里要注意是否是V4包的
(2)開啟一個事務(wù),通過調(diào)用beginTransaction方法開啟。
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
(3)向容器內(nèi)加入Fragment,一般使用add或者replace方法實現(xiàn),需要傳入容器的id和 Fragment的實例。
fragmentTransaction.replace(Activity設(shè)置的布局中的ViewGroup組件id,需要替換的Fragment實例);
//也可以使用三參的方法,傳遞一個Tag
(4)提交事務(wù),調(diào)用commit方法提交。
fragmentTransaction.commit();
(二)Fragment回退棧
類似與Android系統(tǒng)為Activity維護一個任務(wù)棧,我們也可以通過Activity維護一個回退棧來保 存每次Fragment事務(wù)發(fā)生的變化。如果你將Fragment任務(wù)添加到回退棧,當(dāng)用戶點擊后退按鈕時,將看到上一次的保存的Fragment。一旦Fragment完全從后退棧中彈出,用戶再次點擊后退鍵,則退出當(dāng)前Activity。 假設(shè)現(xiàn)在我們有兩個Fragment:Fragment01和Fragment02,我們現(xiàn)在從Fragment01的界面跳到Fragment02,然后按Back鍵,發(fā)現(xiàn)程序是直接退出了,而不是返回到Fragment01。 如果現(xiàn)在想實現(xiàn)以下功能:從Fragment01的界面跳到Fragment02,然后按Back鍵,會返回到Fragment01,就需要加入回退棧了,F(xiàn)ragmentTransaction中提供了一個 addToBackStack()方法,可以將一個事務(wù)添加到返回棧中。
1. transaction.add(R.id.right, rightFragment);
2. transaction.addToBackStack(null);
我們在事務(wù)提交之前調(diào)用了FragmentTransaction的addToBackStack()方法,它可以接受一個名字用于描述返回棧的狀態(tài),一般傳入null即可。
下面是Fragment程序的示例
三.靜態(tài)顯示Fragment碎片頁面,并進行兩碎片頁面的數(shù)據(jù)通信
這里左邊四個按鈕是一個碎片布局,右邊的碎片布局是一個ListView顯示數(shù)據(jù)。
程序運行后效果:

數(shù)據(jù)交換的后的情況:

設(shè)計代碼:
布局文件比較簡單,所以先展示布局文件。再展示java代碼設(shè)計。
(一)布局文件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è)計兩個靜態(tài)的碎片文件,使用的是小寫的fragment標(biāo)簽,里面必須要有name和id(或tag)屬性。
(二)第一個碎片頁面包含的布局文件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="音樂" />
<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>
(三)第二個碎片頁面包含的布局文件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>
(四)第一個碎片頁面的java代碼設(shè)計:
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;
/**
* 碎片頁面A的顯示,這里顯示四個按鈕
*/
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實現(xiàn)的方法,它是返回空值的
return View.inflate(getActivity(), R.layout.fragment_a, null);
}
//這個方法不在Fragment的生命周期里面
//但是它會在onCreateView后面執(zhí)行,里面的參數(shù)View就是上面?zhèn)魅氲膙iew對象
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//實例化布局上的控件
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)聽事件
music.setOnClickListener(this);
sports.setOnClickListener(this);
arts.setOnClickListener(this);
dance.setOnClickListener(this);
}
//實現(xiàn)監(jiān)聽的方法
@Override
public void onClick(View v) {
//獲取頁面碎片B的對象,來對頁面碎片B進行操作,這里不能使用new的方法來創(chuàng)建對象
FragmentB fragmentB = (FragmentB) getActivity().getSupportFragmentManager().findFragmentById(R.id.main_frag2);
switch (v.getId()) {
case R.id.music:
fragmentB.list.add(0, "音樂");//給頁面B的集合中添加數(shù)據(jù)
Toast.makeText(getActivity(), "music", Toast.LENGTH_SHORT).show();
break;
case R.id.sports:
fragmentB.list.add(0, "運動");//給頁面B的集合中添加數(shù)據(jù)
Toast.makeText(getActivity(), "sports", Toast.LENGTH_SHORT).show();
break;
case R.id.arts:
fragmentB.list.add(0, "藝術(shù)");//給頁面B的集合中添加數(shù)據(jù)
Toast.makeText(getActivity(), "arts", Toast.LENGTH_SHORT).show();
break;
case R.id.dance:
fragmentB.list.add(0, "跳舞");//給頁面B的集合中添加數(shù)據(jù)
Toast.makeText(getActivity(), "dance", Toast.LENGTH_SHORT).show();
break;
}
fragmentB.adapter.notifyDataSetChanged();//刷新頁面B的數(shù)據(jù)
}
}
(五)第二個碎片頁面的java代碼設(shè)計
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;
/**
* 碎片頁面B的顯示,這里顯示一個ListView數(shù)據(jù)
*/
public class FragmentB extends Fragment implements AdapterView.OnItemClickListener {
//定義集合、適配器、ListView
List<String> list;
ArrayAdapter<String> adapter;
ListView listView;
//數(shù)據(jù)源的其中一個字符串變量
String name = "music";
/**
* 最先執(zhí)行,一般是處理于界面無關(guān)的數(shù)據(jù)
*/
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//實例化list集合
list = new ArrayList<>();
//實例化ListView
//添加數(shù)據(jù)源
for (int i = 1; i <= 100; i++) {
list.add(name + i);
}
//實例化Adapter對象
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實現(xiàn)的方法,它是返回空值的
return View.inflate(getActivity(), R.layout.fragment_b, null);
}
/***
* fragment創(chuàng)建前最后執(zhí)行的方法
* 加載視圖上面顯示的數(shù)據(jù)和默認設(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添加點擊的監(jiān)聽事件
listView.setOnItemClickListener(this);
//獲取碎片A的對象
fragmentA= (FragmentA) getActivity().getSupportFragmentManager().findFragmentById(R.id.main_frag1);
}
/**
* ListView中點擊對應(yīng)的條目的回調(diào)方法
*/
FragmentA fragmentA;
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//這里修改頁面A中的第一個按鈕的文本
//點擊ListView哪個條目,這個條目的文本都會顯示在第一個按鈕上(實現(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è)計,只需要把布局顯示出來就可以了,這里全部的處理都是在fragment碎片中做好了,這就是碎片的好處。
四.動態(tài)創(chuàng)建碎片的示例
程序運行后的界面:

點擊某個按鈕,選擇顯示對應(yīng)的碎片頁面
代碼設(shè)計:
(一)布局文件設(shè)計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="動態(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>
這里動態(tài)顯示的碎片頁面在先設(shè)置一個FrameLayout布局容器來存放碎片頁面。
下面簡單設(shè)計碎片頁面。
(二)聯(lián)系人頁面碎片
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)系人碎片頁面
*/
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)系人頁面");
textView.setTextSize(30);
return textView;
}
}
(三)消息頁面碎片
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;
/**
* 這是消息頁面的碎片
*/
public class MessageFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
textView.setText("這是消息頁面");
textView.setTextSize(30);
return textView;
}
}
(四)動態(tài)頁面碎片
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;
/**
*這是動態(tài)頁面的碎片
*/
public class NewsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
textView.setText("這是動態(tài)頁面");
textView.setTextSize(30);
return textView;
}
}
(五)動態(tài)頁面碎片
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;
/**
*這是動態(tài)頁面的碎片
*/
public class NewsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
textView.setText("這是動態(tài)頁面");
textView.setTextSize(30);
return textView;
}
}
上面就是四個碎片頁面的設(shè)計,都是比較簡單的頁面設(shè)計,其實也是可以像Activity一樣設(shè)計成一個很復(fù)雜頁面的顯示。
(六)主方法類,重點理解
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;
//定義四個存放碎片的數(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);
//顯示第一個碎片頁面
showFragment(0);
}
/**
* 顯示碎片頁面的方法
* 這里是要重點理解的地方
* 這里要添加和移除的操作都有,而且還有進行一定的判斷
*/
//定義一個當(dāng)前點擊的游標(biāo)值,默認是-1,說明還沒有點
int currentIndex = -1;
private void showFragment(int i) {
//如果點擊的頁面是剛才顯示的頁面,就什么都不做
if (i == currentIndex) {
return;
}
//處理碎片,顯示、移除等等
//這里要用碎片的事務(wù)來完成
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//如果用戶打開已經(jīng)打開過一個Fragment頁面,再打開其他頁面后,要先把原來的頁面移除
if (currentIndex != -1) {
//移除碎片
transaction.hide(fragment[currentIndex]);
}
//顯示新的碎片
if (fragment[i] == null) {
//創(chuàng)建碎片
CreateFragment(i);
//使用事務(wù)顯示碎片
//第一個參數(shù)是碎片要顯示的布局的位置的ID號
//第二個參數(shù)是顯示的碎片的對象
transaction.add(R.id.main_fl, fragment[i]);
} else {
//如果碎片曾經(jīng)顯示過就顯示出來就可以了
transaction.show(fragment[i]);
// transaction.addToBackStack(null);
}
//保存用戶點擊的游標(biāo)值
currentIndex = i;
//最后提交事務(wù),把碎片放置到位
transaction.commit();
}
//初始化數(shù)據(jù)
private void initView() {
//實例化數(shù)據(jù)
radioGroup = (RadioGroup) findViewById(R.id.main_rg);
frameLayout = (FrameLayout) findViewById(R.id.main_fl);
//給GroupButton設(shè)置監(jiān)聽事件
radioGroup.setOnCheckedChangeListener(this);
}
/**
* 按鈕選擇后觸發(fā)的方法
*/
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//點擊哪一個按鈕就顯示哪一個碎片
//這里的checkedID不是0、1、2、3這種數(shù)值,而是布局里面對應(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)建碎片頁面對象的方法
*/
private void CreateFragment(int i) {
//如果碎片是第一次點開,就要創(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;
}
}
}
程序運行后就可以顯示界面了。這就是動態(tài)創(chuàng)建碎片的示例。
五.動態(tài)創(chuàng)建碎片和靜態(tài)創(chuàng)建碎片的對比:
很多人都會有疑問:動態(tài)創(chuàng)建和靜態(tài)創(chuàng)建碎片有什么區(qū)別?
其實主要是應(yīng)用場合的區(qū)別,并且我們也要知道它們的創(chuàng)建的區(qū)別。
(一)碎片靜態(tài)創(chuà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是一個唯一標(biāo)識,是用來找到這個碎片對象用的;而name是繼承了Fragment的自定義類,使用包名+類名設(shè)置。
靜態(tài)創(chuàng)建的碎片一旦創(chuàng)建它就在這個Activity頁面的固定位置了。
2.動態(tài)創(chuàng)建碎片
要在布局文件內(nèi)先創(chuàng)建層布局容器標(biāo)簽FrameLayout,動態(tài)創(chuàng)建的碎片頁面都是顯示在這個容器里面的。這里控制碎片改變是在所依賴的Activity頁面的代碼當(dāng)中來控制。都是通過事務(wù)來顯示或隱藏碎片,達到碎片切換的效果。
(二)靜態(tài)碎片和動態(tài)碎片的應(yīng)用場合1.靜態(tài)碎片的應(yīng)用場合
靜態(tài)碎片的應(yīng)用場合是多個頁面都會出現(xiàn)這種布局,并且它的事件處理是一樣的。
比如下面兩個頁面:
上面兩不同的頁面中,最下方的顯示都是一樣的,并且點擊某個按鈕跳轉(zhuǎn)到的頁面都是一樣的,這時就需要用靜態(tài)的碎片。
使用方法:只要把這個靜態(tài)標(biāo)簽的fragment放到這兩頁面的底部就可以了。
對于上面兩個頁面但是如果你不用使用碎片,就需要在兩個頁面都設(shè)置這幾個控件,并且它們的點擊事件的處理,都要在兩個頁面的Activity中重新做。這就降低了代碼的復(fù)用性。
靜態(tài)碎片是固定的,但是它的事件處理都是已經(jīng)寫好了的,都在自定義的Fragment類中,你使用的使用只要復(fù)制靜態(tài)的xml代碼就可以了。
在開發(fā)中,如果是多個頁面有相同的一些小布局,這時使用靜態(tài)碎片就非常必要了。
2.動態(tài)碎片的應(yīng)用場合
動態(tài)碎片的應(yīng)用場合應(yīng)該是比較容易就看出來的,就是某一個頁面,通過幾個按鈕實現(xiàn)頁面中局部畫面的切換。
最常見的應(yīng)用場合:
這里在同一個Activity中可以顯示多個頁面,并且頁面之間可以實現(xiàn)簡單的切換,這就是動態(tài)創(chuàng)建碎片的應(yīng)用。
在實際開發(fā)中,上面的頁面還要實現(xiàn)左右滑動來切換頁面,這就需要ViewPager,使用ViewPager能非常方便的實現(xiàn)頁面的切換,并且不需要事務(wù)處理。這個知識點后面總結(jié)。
最后簡單說一下:
其實碎片就像一個Activity,它也是可以顯示很多頁面數(shù)據(jù),并且可以實現(xiàn)頁面的跳轉(zhuǎn),數(shù)據(jù)的傳遞。但是它是不用在AndroidManifest中注冊的。
碎片頁面的跳轉(zhuǎn)到其他Activity頁面也是使用startActivity或StartActivityForResult。
數(shù)據(jù)傳遞也是可以通過Intent來攜帶數(shù)據(jù)。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Android開發(fā)實現(xiàn)自定義新聞加載頁面功能實例
這篇文章主要介紹了Android開發(fā)實現(xiàn)自定義新聞加載頁面功能,結(jié)合具體實例形式分析了Android界面加載及頁面布局相關(guān)操作技巧,需要的朋友可以參考下2017-10-10
Android Textview實現(xiàn)顏色漸變滾動效果
這篇文章主要為大家詳細介紹了Android Textview實現(xiàn)顏色漸變滾動效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10
Android TextView實現(xiàn)跑馬燈效果的方法
這篇文章主要介紹了Android TextView跑馬燈效果實現(xiàn)方法,涉及Android布局文件中相關(guān)屬性的設(shè)置技巧,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-01-01
Android APP開發(fā)KML軌跡導(dǎo)出教程示例
這篇文章主要為大家介紹了Android APP開發(fā)KML軌跡導(dǎo)出教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12
Android將Xamarin For VS升級為4.1.0.530版教程
這篇文章主要介紹了Android將Xamarin For VS升級為4.1.0.530版的圖文教程,感興趣的小伙伴們可以參考一下2016-06-06
Android應(yīng)用中使用ViewPager和ViewPager指示器來制作Tab標(biāo)簽
這篇文章主要介紹了Android中使用ViewPager和ViewPager指示器來制作Tab標(biāo)簽的方法,ViewPager指示器ViewPageIndicator是一個開源庫,文中舉了一個仿網(wǎng)易新聞客戶端Tab標(biāo)簽的例子,需要的朋友可以參考下2016-03-03

