Android應(yīng)用開發(fā)中Fragment的靜態(tài)加載與動態(tài)加載實例
1、Fragment的靜態(tài)使用
Fragment是作為Activity的UI的一部分,它內(nèi)嵌在Activity中,多個Fragment可以把一個Activity分成多個部分,這在大屏幕手機(jī)或者平板電腦中會比較多的用到,這樣就不用使用多個Activity來切換這么麻煩了。當(dāng)然Fragment也可以不顯示,只在后臺處理一些數(shù)據(jù),這篇文章中就暫時不談到這個。以下來看怎么靜態(tài)地在Activity的布局文件中添加Fragment.
自定義的Fragment通常要繼承Fragment這個類,也有一些特殊的是繼承ListFragment,DialogFragment等。繼承Fragment類通常要實現(xiàn)三個方法:onCreate(), onCreateView(), onPause();
我在Activity中定義了兩個Fragment,一個是放在左邊的LeftFragment,一個是放在右邊的RightFragment.以下是代碼:首先我們要實現(xiàn)自己的Fragment類
LeftFragment類:
public class LeftFragment extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); System.out.println("LeftFragment onCreate"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { System.out.println("LeftFragment onCreateView"); // 第一個參數(shù)是這個Fragment將要顯示的界面布局,第二個參數(shù)是這個Fragment所屬的Activity,第三個參數(shù)是決定此fragment是否附屬于Activity return inflater.inflate(R.layout.leftfragment, container, true); } @Override public void onResume() { super.onResume(); System.out.println("LeftFragment onResume"); } @Override public void onPause() { super.onPause(); System.out.println("LeftFragment onPause"); } @Override public void onStop() { super.onStop(); System.out.println("LeftFragment onStop"); } }
這里實現(xiàn)了幾種回調(diào)函數(shù),主要是為了看清Activity和Fragment生命周期之間的關(guān)系.其中onCreateView()方法是將本Fragment對應(yīng)的布局返回給Activity的布局,讓Activity進(jìn)行加載. inflater.inflate(R.layout.leftfragment, container, true)方法中的第一個參數(shù)R.layout.leftfragment是這個Fragment對應(yīng)的布局文件ID, 第二個參數(shù)container是要插入的目標(biāo)Activity, 第三個參數(shù)是決定這個Fragment是否依附于這個container.
LeftFragment對應(yīng)的布局文件:
<?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="@android:color/holo_orange_dark" android:orientation="vertical" > <Button android:id="@+id/previous_button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/previous_button" /> <Button android:id="@+id/next_button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/next_button" /> <Button android:id="@+id/exit_button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/exit_button" /> </LinearLayout>
RightFragment類:和LeftFragment類似
public class RightFragment extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); System.out.println("RightFragment onCreate"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { System.out.println("RightFragment onCreateView"); return inflater.inflate(R.layout.rightfragment, container, true); } @Override public void onResume() { super.onResume(); System.out.println("RightFragment onResume"); } @Override public void onPause() { super.onPause(); System.out.println("RightFragment onPause"); } @Override public void onStop() { super.onStop(); System.out.println("RightFragment onStop"); } }
RightFragment對應(yīng)的布局文件:
<?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" > <TextView android:id="@+id/show_message" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@android:color/holo_blue_dark" android:text="@string/show_message" /> </LinearLayout>
最后是Activity的布局文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" > <fragment android:id="@+id/left_fragment" android:name="com.sunflower.LeftFragment" android:layout_width="match_parent" android:layout_height="fill_parent" android:layout_weight="3" /> <fragment android:id="@+id/right_fragment" android:name="com.sunflower.RightFragment" android:layout_width="match_parent" android:layout_height="fill_parent" android:layout_weight="1" /> </LinearLayout>
在Activity中的布局文件中加入Fragment標(biāo)簽,其中android:name屬性對應(yīng)的就是自定義Fragment類的全名,系統(tǒng)會根據(jù)這個調(diào)用指定的Fragment的onCreateView()方法來得到這個Fragment的布局,然后加入Activity中. onCreateView()方法中的Container參數(shù)就是這時候傳遞過去的。
看看顯示結(jié)果:
打開程序時生命周期顯示:
按返回鍵時生命周期顯示:
2、動態(tài)地使用Fragment
上面已經(jīng)演示了最簡單的使用Fragment的方式,下面分享一下如何動態(tài)的添加、更新、以及刪除Fragment。
首先是,MainActivity的布局文件activity_main.xml,該文件布局文件上面的頂部是一個TitleFragment,是一個靜態(tài)聲明的Fragment。
中間也是一個Fragment,但是這個Fragment是動態(tài)使用的。
最下面是四個按鈕。用include標(biāo)簽包含外部的布局文件進(jìn)來的。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <fragment android:id="@+id/id_fragment_title" android:name="com.example.dynamicfragment.TitleFragment" android:layout_width="fill_parent" android:layout_height="45dp" /> <include android:id="@+id/id_ly_bottombar" android:layout_width="fill_parent" android:layout_height="55dp" android:layout_alignParentBottom="true" layout="@layout/bottombar" /> <FrameLayout android:id="@+id/id_content" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_above="@id/id_ly_bottombar" android:layout_below="@id/id_fragment_title" /> </RelativeLayout>
然后是,MainActivity.java文件。也是我們這個demo當(dāng)中最重要的代碼文件,首先是將上面的布局文件通過setContentView()加載進(jìn)來.然后是通過setDefaultFragment();將默認(rèn)的ContentFragment動態(tài)的加載進(jìn)來。接下來就是通過我們在最下面防止的四個按鈕可以隨意的動態(tài)切換Fragment。這也是為什么Fragment會有如此火的原因吧~~~^^
public class MainActivity extends ActionBarActivity implements OnClickListener { private ImageButton mTabWeixin; private ImageButton mTabFriend; private ImageButton mTabDiscover; private ImageButton mTabMe; private ContentFragment mWeiXinFragment; private FriendFragment mFriendFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); initView(); } public void initView() { // 初始化控件和聲明事件 mTabWeixin = (ImageButton) findViewById(R.id.weixin); mTabFriend = (ImageButton) findViewById(R.id.friend); mTabWeixin.setOnClickListener(this); mTabFriend.setOnClickListener(this); // 設(shè)置默認(rèn)的Fragment setDefaultFragment(); } @SuppressLint("NewApi") private void setDefaultFragment() { FragmentManager manager = getFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); mWeiXinFragment = new ContentFragment(); transaction.replace(R.id.id_content, mWeiXinFragment); transaction.commit(); } @SuppressLint("NewApi") @Override public void onClick(View v) { FragmentManager fm = getFragmentManager(); // 開啟Fragment事務(wù) FragmentTransaction transaction = fm.beginTransaction(); switch (v.getId()) { case R.id.weixin: if (mWeiXinFragment == null) { mWeiXinFragment = new ContentFragment(); } // 使用當(dāng)前Fragment的布局替代id_content的控件 transaction.replace(R.id.id_content, mWeiXinFragment); break; case R.id.friend: if (mFriendFragment == null) { mFriendFragment = new FriendFragment(); } transaction.replace(R.id.id_content, mFriendFragment); break; } // transaction.addToBackStack(); // 事務(wù)提交 transaction.commit(); } }
從上面的代碼,我們可以看出,我們可以使用FragmentManager對Fragment進(jìn)行動態(tài)的加載,這里使用的replace方法~~~下一節(jié)我們會詳細(xì)的介紹FragmentManager的常用API。。。。^^
注:如果使用android3.0一下的版本,需要引入v4的包,然后Activity繼承FragmentActivity,然后通過getSupportFragmentManager()獲得FragmentManager對象,不過還是建議把Menifest文件的uses-sdk的minSdkVersion和targetSdkVersion都改為11以上,這樣就不必引入v4的包了。
代碼的中間有倆個動態(tài)加載進(jìn)來的Fragment,這個和靜態(tài)使用Fragment的聲明方式是一樣的,寫一個繼承Fragment的類,然后設(shè)置相應(yīng)的布局,由于時間的關(guān)系,我這里只寫了倆個Fragment,現(xiàn)在把這倆個的代碼頁貼出來:
第一個Fragment和他相應(yīng)的布局文件:
public class ContentFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_content, container, false); } }
<?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" > <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:text="weixin" android:textSize="20sp" android:textStyle="bold" /> </LinearLayout>
第二個Fragment和他相應(yīng)的布局文件:
public class FriendFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_friend, container, false); } }
<?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" > <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:text="friend" android:textSize="20sp" android:textStyle="bold" /> </LinearLayout>
好了,現(xiàn)在基本的代碼都有了,我們把demo的運行圖貼出來給大家分享一下(注:時間原因,沒注意布局以及圖片的美化,只是功能的實現(xiàn)),這是分別點擊下面第一個和第二個按鈕的效果圖,從而實現(xiàn)了中間用一個Fragment動態(tài)的加載這倆個Fragment的顯示。
ps:為了代碼的簡潔,就不添加按鈕的點擊變化什么的了,主要講解功能了~~~
相關(guān)文章
android開發(fā)之蜂鳴提示音和震動提示的實現(xiàn)原理與參考代碼
蜂鳴提示音和震動提示此功能在手機(jī)使用中很實用,最近在讀zxing項目,學(xué)到了不少東西;我們一起來看看他是怎么做的,感興趣的朋友可以了解下哦2013-01-01新浪微博第三方登錄界面上下拉伸圖片之第三方開源PullToZoomListViewEx(二)
這篇文章主要介紹了新浪微博第三方登錄界面上下拉伸圖片之第三方開源PullToZoomListViewEx(二) 的相關(guān)資料,需要的朋友可以參考下2015-12-12Android 中ListView和GridView賦值錯位
這篇文章主要介紹了Android 中ListView和GridView賦值錯位的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下2017-10-10AndroidUI組件SlidingTabLayout實現(xiàn)ViewPager頁滑動效果
這篇文章主要介紹了AndroidUI組件SlidingTabLayout實現(xiàn)ViewPager頁滑動效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-10-10GuideView的封裝實現(xiàn)app功能引導(dǎo)頁
這篇文章主要為大家詳細(xì)介紹了GuideView的封裝實現(xiàn)app功能引導(dǎo)頁,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-03-03Android使用元數(shù)據(jù)實現(xiàn)配置信息的傳遞方法詳細(xì)介紹
這篇文章主要介紹了Android使用元數(shù)據(jù)實現(xiàn)配置信息的傳遞方法,也就是實現(xiàn)配置快捷菜單功能,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-09-09