Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

用 Fragment 打造同時兼容手機與平板板的 Android 程式

編輯:Android 開發實例

早年間我參與過一個華為的專案,要求程式同時支援多種終端,其中就包含 Android 手機與 Android Pad。為了省人力,公司毫不客氣地把手機版與平板版都丟給了我們團隊。當時定下的方案很樸素:做兩個版本的 App,一個手機版、一個 Pad 版。由於手機版主力功能已大致完成,Pad 版基本上就是把手機版程式碼整份搬過來,再針對平板特性微調一下了事。

然而,從那時起我們就陷入了漫長的折磨。每加一個新功能,同樣的程式碼得寫兩遍;每修一個 bug,手機版與 Pad 版各改一次。這還不算什麼,一到發版才是真正的惡夢。華為要求每次都要出兩個版本——一個內網環境版、一個客戶現場版,如今又分手機與 Pad,等於每次得出四個包。要是發完版自測又冒出問題,那就準備通宵吧。這尤其苦了我們的 X 總(因為他 Dota 打得好,我私下都叫他 X 神)。他獨自扛著一個模組,每次打包又都由他負責,加班的時候我們都能溜,唯獨他溜不掉。這裡也要給 X 神的敬業精神點個讚,要是他看得到的話。

熬過那段日子後,我便開始琢磨:能不能做出一個同時兼容手機與平板的 App 呢?答案當然是可以,無奈我這人比較散,一直提不起勁去鑽研。直到一位在美國留學的朋友 Gong 找我幫她解決研究生導師佈置的作業(我知道你導師看不懂中文 ^-^),剛好就落在這個主題上,我也趁機研究了一番,現在拿出來與大家分享。

先看看 Android 手機的設定介面:點一下 Sound,會跳轉到聲音設定頁,如下面兩張圖:

           
 

再看看 Android Pad 的設定介面:主設定頁與聲音設定頁會同時顯示在同一個畫面上,如下圖:


 

如果這兩種效果出自兩個不同的 App,那沒什麼好驚喜的;但如果是同一個 App,在手機與平板上各自呈現上述兩種樣貌,你是不是已經有點心動了?我們現在就來模擬實作。

首先你得對 Fragment 有基本認識,若還沒接觸過,建議先讀讀 https://www.fengfly.com/plus/view-215089-1.html 這篇文章。另外本次程式碼運行於 Android 4.0,如果你的 SDK 版本偏低,建議先升升級。

新建一個名為 FragmentDemo 的專案。打開或建立 MainActivity,裡面是自動生成的內容:

  1. public class MainActivity extends Activity {  
  2.  
  3.     @Override 
  4.     public void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main);  
  7.     }  
  8.  
  9. }  

對老手來說,這段程式碼實在太家常了,每個 Activity 開頭都長這樣。不過今天的主角可沒這麼單純,載入布局這一塊大有學問。

 

打開或建立 res/layout/activity_main.xml 作為主布局:

  1. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  2.     xmlns:tools="https://schemas.android.com/tools" 
  3.     android:layout_width="fill_parent" 
  4.     android:layout_height="fill_parent" 
  5.     android:orientation="horizontal" 
  6.     tools:context=".MainActivity" > 
  7.  
  8.     <fragment 
  9.         android:id="@+id/menu_fragment" 
  10.         android:name="com.example.fragmentdemo.MenuFragment" 
  11.         android:layout_width="fill_parent" 
  12.         android:layout_height="fill_parent" /> 
  13.  
  14. </LinearLayout> 

這個布局引用了一個 MenuFragment,我們稍後再實作。先看今天的重點之一:我們需要再建一個檔名同樣是 activity_main.xml 的布局,但要放在不同的目錄下。

在 res 目錄下新建 layout-large 目錄,並在其中建立 activity_main.xml:

  1. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  2.     xmlns:tools="https://schemas.android.com/tools" 
  3.     android:layout_width="fill_parent" 
  4.     android:layout_height="fill_parent" 
  5.     android:orientation="horizontal" 
  6.     android:baselineAligned="false" 
  7.     tools:context=".MainActivity" 
  8.     > 
  9.  
  10.     <fragment 
  11.         android:id="@+id/left_fragment" 
  12.         android:name="com.example.fragmentdemo.MenuFragment" 
  13.         android:layout_width="0dip" 
  14.         android:layout_height="fill_parent" 
  15.         android:layout_weight="1" /> 
  16.       
  17.     <FrameLayout   
  18.         android:id="@+id/details_layout" 
  19.         android:layout_width="0dip" 
  20.         android:layout_height="fill_parent" 
  21.         android:layout_weight="3" 
  22.         ></FrameLayout> 
  23.  
  24. </LinearLayout> 

 

這個布局同樣引用了 MenuFragment,另外多了一個 FrameLayout 用來承載詳細內容,分別對應平板畫面上的左側與右側區域。

這裡用到了動態載入布局的技巧:Activity 呼叫 setContentView(R.layout.activity_main) 表明要載入 activity_main,而 Android 系統會依當前運行環境判斷是否為大螢幕裝置——若是,就載入 layout-large 目錄下的版本,否則預設載入 layout 目錄下的版本。

關於動態載入布局的更多細節,可參考 https://www.fengfly.com/plus/view-215087-1.html 這篇文章。

下面來實作 MenuFragment。新建一個繼承自 Fragment 的類別:

  1. public class MenuFragment extends Fragment implements OnItemClickListener {  
  2.  
  3.     /**  
  4.      * 菜單界面中只包含了一個ListView。  
  5.      */ 
  6.     private ListView menuList;  
  7.  
  8.     /**  
  9.      * ListView的適配器。  
  10.      */ 
  11.     private ArrayAdapter<String> adapter;  
  12.  
  13.     /**  
  14.      * 用于填充ListView的數據,這里就簡單只用了兩條數據。  
  15.      */ 
  16.     private String[] menuItems = { "Sound", "Display" };  
  17.  
  18.     /**  
  19.      * 是否是雙頁模式。如果一個Activity中包含了兩個Fragment,就是雙頁模式。  
  20.      */ 
  21.     private boolean isTwoPane;  
  22.  
  23.     /**  
  24.      * 當Activity和Fragment建立關聯時,初始化適配器中的數據。  
  25.      */ 
  26.     @Override 
  27.     public void onAttach(Activity activity) {  
  28.         super.onAttach(activity);  
  29.         adapter = new ArrayAdapter<String>(activity, android.R.layout.simple_list_item_1, menuItems);  
  30.     }  
  31.  
  32.     /**  
  33.      * 加載menu_fragment布局文件,為ListView綁定了適配器,并設置了監聽事件。  
  34.      */ 
  35.     @Override 
  36.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  37.         View view = inflater.inflate(R.layout.menu_fragment, container, false);  
  38.         menuList = (ListView) view.findViewById(R.id.menu_list);  
  39.         menuList.setAdapter(adapter);  
  40.         menuList.setOnItemClickListener(this);  
  41.         return view;  
  42.     }  
  43.  
  44.     /**  
  45.      * 當Activity創建完畢后,嘗試獲取一下布局文件中是否有details_layout這個元素,如果有說明當前  
  46.      * 是雙頁模式,如果沒有說明當前是單頁模式。  
  47.      */ 
  48.     @Override 
  49.     public void onActivityCreated(Bundle savedInstanceState) {  
  50.         super.onActivityCreated(savedInstanceState);  
  51.         if (getActivity().findViewById(R.id.details_layout) != null) {  
  52.             isTwoPane = true;  
  53.         } else {  
  54.             isTwoPane = false;  
  55.         }  
  56.     }  
  57.  
  58.     /**  
  59.      * 處理ListView的點擊事件,會根據當前是否是雙頁模式進行判斷。如果是雙頁模式,則會動態添加Fragment。  
  60.      * 如果不是雙頁模式,則會打開新的Activity。  
  61.      */ 
  62.     @Override 
  63.     public void onItemClick(AdapterView<?> arg0, View view, int index, long arg3) {  
  64.         if (isTwoPane) {  
  65.             Fragment fragment = null;  
  66.             if (index == 0) {  
  67.                 fragment = new SoundFragment();  
  68.             } else if (index == 1) {  
  69.                 fragment = new DisplayFragment();  
  70.             } 
  71.             getFragmentManager().beginTransaction().replace(R.id.details_layout, fragment).commit();  
  72.         } else {  
  73.             Intent intent = null;  
  74.             if (index == 0) {  
  75.                 intent = new Intent(getActivity(), SoundActivity.class);  
  76.             } else if (index == 1) {  
  77.                 intent = new Intent(getActivity(), DisplayActivity.class);  
  78.             }  
  79.             startActivity(intent);  
  80.         }  
  81.     }  
  82.  
  83. }  

這個類別不長,我簡單說明一下:onCreateView 載入 menu_fragment 布局,其中含有一個 ListView,我們為它填入 "Sound" 與 "Display" 兩筆資料;onActivityCreated 則做了一個判斷,若 Activity 布局裡存在 details_layout,就是雙頁模式,否則為單頁模式;onItemClick 負責處理點擊——雙頁模式下動態往 details_layout 塞入 Fragment,單頁模式下則直接開啟新 Activity。

 

接著把 MenuFragment 引用到的其他內容一一補齊。新建 menu_fragment.xml:

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="fill_parent" 
  4.     android:layout_height="fill_parent" > 
  5.       
  6.     <ListView 
  7.         android:id="@+id/menu_list" 
  8.         android:layout_width="fill_parent" 
  9.         android:layout_height="fill_parent" 
  10.         ></ListView> 
  11.  
  12. </LinearLayout> 

再來新建 SoundFragment,內容非常精簡:

  1. public class SoundFragment extends Fragment {  
  2.  
  3.     @Override 
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  5.         View view = inflater.inflate(R.layout.sound_fragment, container, false);  
  6.         return view;  
  7.     }  
  8.  
  9. } 

SoundFragment 需要 sound_fragment.xml,於是新建這個布局:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" 
  5.     android:background="#00ff00" 
  6.     android:orientation="vertical" > 
  7.       
  8.     <TextView   
  9.         android:layout_width="wrap_content" 
  10.         android:layout_height="wrap_content" 
  11.         android:layout_centerInParent="true" 
  12.         android:textSize="28sp" 
  13.         android:textColor="#000000" 
  14.         android:text="This is sound view" 
  15.         /> 
  16.  
  17. </RelativeLayout> 

同理,再建立 DisplayFragment 與 display_fragment.xml:

 

  1. public class DisplayFragment extends Fragment {  
  2.  
  3.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  4.         View view = inflater.inflate(R.layout.display_fragment, container, false);  
  5.         return view;  
  6.     }  
  7.  
  8. } 
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" 
  5.     android:background="#0000ff" 
  6.     android:orientation="vertical" > 
  7.       
  8.     <TextView   
  9.         android:layout_width="wrap_content" 
  10.         android:layout_height="wrap_content" 
  11.         android:layout_centerInParent="true" 
  12.         android:textSize="28sp" 
  13.         android:textColor="#000000" 
  14.         android:text="This is display view" 
  15.         /> 
  16.  
  17. </RelativeLayout> 

接著新建 SoundActivity:

  1. public class SoundActivity extends Activity {  
  2.  
  3.     @Override 
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.sound_activity);  
  7.     }  
  8.  
  9. } 

這個 Activity 只是載入一個布局,我們來寫 sound_activity.xml:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <fragment xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:id="@+id/sound_fragment" 
  4.     android:name="com.example.fragmentdemo.SoundFragment" 
  5.     android:layout_width="match_parent" 
  6.     android:layout_height="match_parent" > 
  7.  
  8. </fragment> 

這個布局引用了 SoundFragment,好處是日後只要改動 SoundFragment,SoundActivity 就會自動跟著變化,因為它的一切都源自 SoundFragment。

同樣的手法,我們再完成 DisplayActivity:

  1. public class DisplayActivity extends Activity {  
  2.  
  3.     @Override 
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.display_activity);  
  7.     }  
  8.  
  9. } 

接著加入 display_activity.xml:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <fragment xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:id="@+id/display_fragment" 
  4.     android:name="com.example.fragmentdemo.DisplayFragment" 
  5.     android:layout_width="match_parent" 
  6.     android:layout_height="match_parent" > 
  7.  
  8. </fragment> 

所有程式碼到此完成,來看看成果。

 

先把程式跑在手機上:


 

分別點擊 Sound 與 Display,畫面會跳轉到聲音與顯示頁:

           

再把程式跑在平板上,點擊 Sound:


 

接著點擊 Display 切換到顯示頁:


 

至此,我們成功讓同一個程式同時兼容手機與平板。當然這只是個簡易 demo,更複雜的應用還需要各位自行發揮。

今天的講解就到這裡,有疑問的朋友歡迎在下方留言。

源碼下載,請點擊這裡
 

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved