Android手機平板兩不誤,使用Fragment實現兼容手機和平板的程序

記得我以前參與開發過一個華爲的項目,要求程序能夠支持好幾種終端設備,其中就包括Android手機和Android Pad。而後爲了節省人力,公司無節操地讓Android手機和Android Pad都由咱們團隊開發。當時項目組定的方案是,製做兩個版本的App,一個手機版,一個Pad版。因爲當時手機版的主體功能已經作的差很少了,因此Pad版基本上就是把手機版的代碼徹底拷過來,而後再根據平板的特性部分稍做修改就行了。

可是,今後之後咱們就很是苦逼了。每次要添加什麼新功能,一樣的代碼要寫兩遍。每次要修復任何bug,都要在手機版代碼和Pad版代碼裏各修改一遍。這還不算什麼,每到出版本的時候就更離譜了。華爲要求每次須要出兩個版本,一個華爲內網環境的版本,一個客戶現場的版本,而如今又分了手機和Pad,也就是每次須要出四個版本。若是在出完版本後自測還出現了問題,就能夠直接通宵了。這尤爲是苦了咱們的X總(因爲他dota打的比較好,我都喜歡叫他X神)。他在咱們項目組中單獨維護一個模塊,而且每次打版本都是由他負責,加班的時候咱們都能跑,就是他跑不了。這裏也是讚賞一下咱們X神的敬業精神,若是他看獲得的話。 html

經歷過那麼苦逼時期的我也就開始思考,可不能夠製做同時兼容手機和平板的App呢?答案固然是確定的,不過我這我的比較懶,一直也提不起精神去鑽研這個問題。直到我一個在美國留學的朋友Gong讓我幫她解決她的研究生導師佈置的做業(我知道你研究生導師看不懂中文 ^-^),正好涉及到了這一塊,也就藉此機會研究了一下,如今拿出來跟你們分享。 java

咱們先來看一下Android手機的設置界面,點擊一下Sound,能夠跳轉到聲音設置界面,以下面兩張圖所示: android

          

而後再來看一下Android Pad的設置界面,主設置頁面和聲音設置頁面都是在一個界面顯示的,以下圖所示: ide

若是這分別是兩個不一樣的App作出的效果,那沒有絲毫驚奇之處。但若是是同一個App,在手機上和平板上運行分別有以上兩種效果的話,你是否是就已經心動了?咱們如今就來模擬實現一下。 佈局

首先你須要對Fragment有必定的瞭解,若是你還沒接觸過Fragment,建議能夠先閱讀 Android Fragment徹底解析,關於碎片你所需知道的一切 這篇文章。而且本次的代碼是運行在Android 4.0版本上的,若是你的SDK版本還比較低的話,建議能夠先升升級了。 this

新建一個Android項目,取名叫FragmentDemo。打開或新建MainActivity做爲程序的主Activity,裏面有以下自動生成的內容: spa

  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.  

public class MainActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

}

做爲一個Android老手,上面的代碼實在過小兒科了,每一個Activity中都會有這樣的代碼。不過今天咱們的程序可不會這麼簡單,加載佈局這一塊仍是大有文章的。

打開或新建res/layout/activity_main.xml做爲程序的主佈局文件,裏面代碼以下: .net

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  2.     xmlns:tools="http://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.  
  15. </LinearLayout> 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/menu_fragment"
        android:name="com.example.fragmentdemo.MenuFragment"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />

</LinearLayout>

這個佈局引用了一個MenuFragment,咱們稍後來進行實現,先來看一下今天的一個重點,咱們須要再新建一個activity_main.xml,這個佈局文件名和前面的主佈局文件名是同樣的,可是要放在不一樣的目錄下面。

在res目錄下新建layout-large目錄,而後這個目錄下建立新的activity_main.xml,加入以下代碼: code

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  2.     xmlns:tools="http://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.      
  18.     <FrameLayout  
  19.         android:id="@+id/details_layout" 
  20.         android:layout_width="0dip" 
  21.         android:layout_height="fill_parent" 
  22.         android:layout_weight="3" 
  23.         ></FrameLayout> 
  24.  
  25. </LinearLayout> 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:baselineAligned="false"
    tools:context=".MainActivity"
    >

    <fragment
        android:id="@+id/left_fragment"
        android:name="com.example.fragmentdemo.MenuFragment"
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        />
    
    <FrameLayout 
        android:id="@+id/details_layout"
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="3"
        ></FrameLayout>

</LinearLayout>

這個佈局一樣也引用了MenuFragment,另外還加入了一個FrameLayout用於顯示詳細內容。其實也就是分別對應了平板界面上的左側佈局和右側佈局。 xml

這裏用到了動態加載佈局的技巧,首先Activity中調用 setContentView(R.layout.activity_main) ,代表當前的Activity想加載activity_main這個佈局文件。而Android系統又會根據當前的運行環境判斷程序是否運行在大屏幕設備上,若是運行在大屏幕設備上,就加載layout-large目錄下的activity_main.xml,不然就默認加載layout目錄下的activity_main.xml。

關於動態加載佈局的更多內容,能夠閱讀 Android官方提供的支持不一樣屏幕大小的所有方法 這篇文章。

下面咱們來實現久違的MenuFragment,新建一個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.  

public class MenuFragment extends Fragment implements OnItemClickListener {

	/**
	 * 菜單界面中只包含了一個ListView。
	 */
	private ListView menuList;

	/**
	 * ListView的適配器。
	 */
	private ArrayAdapter<String> adapter;

	/**
	 * 用於填充ListView的數據,這裏就簡單隻用了兩條數據。
	 */
	private String[] menuItems = { "Sound", "Display" };

	/**
	 * 是不是雙頁模式。若是一個Activity中包含了兩個Fragment,就是雙頁模式。
	 */
	private boolean isTwoPane;

	/**
	 * 當Activity和Fragment創建關聯時,初始化適配器中的數據。
	 */
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		adapter = new ArrayAdapter<String>(activity, android.R.layout.simple_list_item_1, menuItems);
	}

	/**
	 * 加載menu_fragment佈局文件,爲ListView綁定了適配器,並設置了監聽事件。
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.menu_fragment, container, false);
		menuList = (ListView) view.findViewById(R.id.menu_list);
		menuList.setAdapter(adapter);
		menuList.setOnItemClickListener(this);
		return view;
	}

	/**
	 * 當Activity建立完畢後,嘗試獲取一下佈局文件中是否有details_layout這個元素,若是有說明當前
	 * 是雙頁模式,若是沒有說明當前是單頁模式。
	 */
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		if (getActivity().findViewById(R.id.details_layout) != null) {
			isTwoPane = true;
		} else {
			isTwoPane = false;
		}
	}

	/**
	 * 處理ListView的點擊事件,會根據當前是不是雙頁模式進行判斷。若是是雙頁模式,則會動態添加Fragment。
	 * 若是不是雙頁模式,則會打開新的Activity。
	 */
	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int index, long arg3) {
		if (isTwoPane) {
			Fragment fragment = null;
			if (index == 0) {
				fragment = new SoundFragment();
			} else if (index == 1) {
				fragment = new DisplayFragment();
			}
			getFragmentManager().beginTransaction().replace(R.id.details_layout, fragment).commit();
		} else {
			Intent intent = null;
			if (index == 0) {
				intent = new Intent(getActivity(), SoundActivity.class);
			} else if (index == 1) {
				intent = new Intent(getActivity(), DisplayActivity.class);
			}
			startActivity(intent);
		}
	}

}

這個類的代碼並不長,我簡單的說明一下。在onCreateView方法中加載了menu_fragment這個佈局,這個佈局裏面包含了一個ListView,而後咱們對這個ListView填充了兩個簡單的數據 "Sound" 和 "Display" 。又在onActivityCreated方法中作了一個判斷,若是Activity的佈局中包含了details_layout這個元素,那麼當前就是雙頁模式,不然就是單頁模式。onItemClick方法則處理了ListView的點擊事件,發現若是當前是雙頁模式,就動態往details_layout中添加Fragment,若是當前是單頁模式,就直接打開新的Activity。

咱們把MenuFragment中引用到的其它內容一個個添加進來。新建menu_fragment.xml文件,加入以下代碼:

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <LinearLayout xmlns:android="http://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> 

<?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" >
    
    <ListView
        android:id="@+id/menu_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        ></ListView>

</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.  

public class SoundFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.sound_fragment, container, false);
		return view;
	}

}

這裏SoundFragment須要用到sound_fragment.xml佈局文件,所以這裏咱們新建這個佈局文件,並加入以下代碼:
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <RelativeLayout xmlns:android="http://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> 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00ff00"
    android:orientation="vertical" >
    
    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="28sp"
        android:textColor="#000000"
        android:text="This is sound view"
        />

</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.     } 

public class DisplayFragment extends Fragment {

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.display_fragment, container, false);
		return view;
	}
}

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <RelativeLayout xmlns:android="http://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> 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0000ff"
    android:orientation="vertical" >
    
    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="28sp"
        android:textColor="#000000"
        android:text="This is display view"
        />

</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.  

public class SoundActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sound_activity);
	}

}

這個Activity只是加載了一個佈局文件,如今咱們來實現sound_activity.xml這個佈局文件:
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <fragment xmlns:android="http://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> 

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/sound_fragment"
    android:name="com.example.fragmentdemo.SoundFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</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.  

public class DisplayActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.display_activity);
	}

}

而後加入display_activity.xml:
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <fragment xmlns:android="http://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> 

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/display_fragment"
    android:name="com.example.fragmentdemo.DisplayFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</fragment>

如今全部的代碼就都已經完成了,咱們來看一下效果吧。

首先將程序運行在手機上,效果圖以下:

分別點擊Sound和Display,界面會跳轉到聲音和顯示界面:

          

而後將程序在平板上運行,點擊Sound,效果圖以下:

而後點擊Display切換到顯示界面,效果圖以下:

這樣咱們就成功地讓程序同時兼容手機和平板了。固然,這只是一個簡單的demo,更多複雜的內容須要你們本身去實現了。

相關文章
相關標籤/搜索