編輯:關於 Android 程式設計
1、Fragment 的靜態使用
Fragment 作為 Activity 介面的一部分,是內嵌在 Activity 之中的。多個 Fragment 可以把一個 Activity 切分成若干區塊,這在智慧型手機的大螢幕機型或平板電腦上應用得尤為頻繁,如此一來,便不必再靠多個 Activity 之間繁瑣的切換來完成。當然,Fragment 也可以不具備可視介面,僅在後台默默處理資料,本文暫且不展開討論這一點。下面我們就來看看,如何靜態地在 Activity 的佈局檔案中嵌入 Fragment。
自訂的 Fragment 通常要繼承 Fragment 類,也有一些特殊的情況會去繼承 ListFragment、DialogFragment 等。繼承 Fragment 類時,一般需要實作三個方法:onCreate()、onCreateView()、onPause()。
我在 Activity 中定義了兩個 Fragment:一個是擺放在左側的 LeftFragment,一個是擺放在右側的 RightFragment。以下是程式碼:首先,我們要實作自己的 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"); // 第一個參數是這個Fragment將要顯示的界面布局,第二個參數是這個Fragment所屬的Activity,第三個參數是決定此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"); } } 這裡實作了幾個回調函式,主要目的是為了看清 Activity 與 Fragment 生命週期之間的關聯。其中 onCreateView() 方法負責把本 Fragment 對應的佈局交還給 Activity 的佈局,交由 Activity 載入。而 inflater.inflate(R.layout.leftfragment, container, true) 方法中的第一個參數 R.layout.leftfragment 是這個 Fragment 對應的佈局檔案 ID,第二個參數 container 是要插入的目標 Activity,第三個參數則用來決定這個 Fragment 是否依附於該 container。
LeftFragment 對應的佈局檔案:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://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 對應的佈局檔案:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://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="https://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 標籤,其中 android:name 屬性對應的便是自訂 Fragment 類的完整名稱,系統會依據這個名稱去呼叫指定 Fragment 的 onCreateView() 方法來取得它的佈局,隨後將其加入 Activity。而 onCreateView() 方法中的 Container 參數,正是在這個時刻被傳遞進來的。
來看看顯示結果:

打開程式時的生命週期顯示:

按下返回鍵時的生命週期顯示:

2、動態地使用 Fragment
上面已經演示了最為簡單的 Fragment 使用方式,接下來分享一下如何動態地添加、更新以及刪除 Fragment。
首先是 MainActivity 的佈局檔案 activity_main.xml,這個檔案頂部是一個 TitleFragment,屬於靜態聲明的 Fragment。
中間同樣是一個 Fragment,不過它是動態使用的。
最下方是四個按鈕,透過 include 標籤把外部的佈局檔案引入進來。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://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 中最關鍵的程式碼檔案。首先是透過 setContentView() 把上面的佈局檔案載入進來,接著由 setDefaultFragment() 把預設的 ContentFragment 動態載入。此後,便能透過擺放在最下方的四個按鈕隨意地動態切換 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); // 設置默認的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事務 FragmentTransaction transaction = fm.beginTransaction(); switch (v.getId()) { case R.id.weixin: if (mWeiXinFragment == null) { mWeiXinFragment = new ContentFragment(); } // 使用當前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(); // 事務提交 transaction.commit(); } } 從上面的程式碼不難看出,我們可以借助 FragmentManager 對 Fragment 進行動態載入,這裡採用的正是 replace 方法~~~下一節我們會詳細介紹 FragmentManager 的常用 API。。。。^^
註:如果使用 Android 3.0 以下的版本,需要引入 v4 的套件包,然後讓 Activity 繼承 FragmentActivity,再透過 getSupportFragmentManager() 取得 FragmentManager 物件;不過還是建議把 Manifest 檔案中 uses-sdk 的 minSdkVersion 與 targetSdkVersion 都設為 11 以上,如此一來便無須再引入 v4 的套件包了。
程式碼中間有兩個動態載入的 Fragment,它們的聲明方式與靜態使用 Fragment 時並無二致:寫一個繼承 Fragment 的類,然後設定相應的佈局。由於時間關係,這裡我只寫了兩個 Fragment,現在把這兩個的程式碼也一併貼出來:
第一個 Fragment 及其對應的佈局檔案:
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="https://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:text /> </LinearLayout>
第二個 Fragment 及其對應的佈局檔案:
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="https://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:text /> </LinearLayout>
好了,基本的程式碼都齊備了,我們把 demo 的運行圖貼出來與大家分享一番(註:由於時間關係,沒能在佈局與圖片美化上多下功夫,重點放在功能的實現上)。這是分別點擊下方第一個與第二個按鈕的效果圖,由此便實現了在中間用一個 Fragment 動態載入這兩個 Fragment 的顯示。


ps:為了讓程式碼更簡潔,就不再添加按鈕的點擊變化等細節了,主要還是講解功能~~~
用Matrix實現圖片倒影效果的三個關鍵步驟
本文的目標是用 Matrix 搭配漸變色,做出圖片的倒影效果。思路可以拆成三步: 1. 取得需要倒影的原圖,這裡只取原圖的下半部分作為倒影素材。 2. 用 Matrix
Android Studio 添加 Parcelable 序列化插件
Android Studio 可安裝插件提升開發效率。本文介紹如何安裝 Parcelable 代碼生成插件,並用它快速實現對象序列化。Android 中常見序列化方式有
Android WebView 實戰技巧整理:標題抓取、檔案下載、錯誤處理與 Cookie 同步
前陣子做專案時用到了 WebView,途中遇到不少問題,於是找資料逐一解決,順手整理成這篇筆記,方便日後快速查閱。 先說背景:Android 的 WebView 是一個相
手機QQ怎麼省流量 一個開關屏蔽群聊圖片
是不是總覺得流量不夠用?仔細回想才發現,流量都耗在手機QQ的群聊裡了。現在手上的QQ群越來越多,群友又愛發圖片與視頻,那該怎麼省下這部分消耗?下面就一起來看。 手機QQ省