編輯: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,裡面是自動生成的內容:
- public class MainActivity extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- }
- }
對老手來說,這段程式碼實在太家常了,每個 Activity 開頭都長這樣。不過今天的主角可沒這麼單純,載入布局這一塊大有學問。
打開或建立 res/layout/activity_main.xml 作為主布局:
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- xmlns:tools="https://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:
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- xmlns:tools="https://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 用來承載詳細內容,分別對應平板畫面上的左側與右側區域。
這裡用到了動態載入布局的技巧:Activity 呼叫 setContentView(R.layout.activity_main) 表明要載入 activity_main,而 Android 系統會依當前運行環境判斷是否為大螢幕裝置——若是,就載入 layout-large 目錄下的版本,否則預設載入 layout 目錄下的版本。
關於動態載入布局的更多細節,可參考 https://www.fengfly.com/plus/view-215087-1.html 這篇文章。
下面來實作 MenuFragment。新建一個繼承自 Fragment 的類別:
- 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,我們為它填入 "Sound" 與 "Display" 兩筆資料;onActivityCreated 則做了一個判斷,若 Activity 布局裡存在 details_layout,就是雙頁模式,否則為單頁模式;onItemClick 負責處理點擊——雙頁模式下動態往 details_layout 塞入 Fragment,單頁模式下則直接開啟新 Activity。
接著把 MenuFragment 引用到的其他內容一一補齊。新建 menu_fragment.xml:
- <?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" >
- <ListView
- android:id="@+id/menu_list"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- ></ListView>
- </LinearLayout>
再來新建 SoundFragment,內容非常精簡:
- 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,於是新建這個布局:
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="https://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:
- 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;
- }
- }
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="https://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:
- public class SoundActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.sound_activity);
- }
- }
這個 Activity 只是載入一個布局,我們來寫 sound_activity.xml:
- <?xml version="1.0" encoding="utf-8"?>
- <fragment xmlns:android="https://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:
- public class DisplayActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.display_activity);
- }
- }
接著加入 display_activity.xml:
- <?xml version="1.0" encoding="utf-8"?>
- <fragment xmlns:android="https://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,更複雜的應用還需要各位自行發揮。
今天的講解就到這裡,有疑問的朋友歡迎在下方留言。
源碼下載,請點擊這裡
Android JSON 解析的關鍵細節:從資料結構到型別對應
JSON 是 JavaScript Object Notation 的縮寫,但今天的它早已與 JavaScript 脫鉤,成為一門語言中立的資料交換格式。相較於 XML,
Android JSON 解析入門:從天氣 API 擷取資料
JSON 是應用程式之間常見的資料交換格式,因為結構清楚、易於閱讀,也方便在 Android 中處理。當 App 需要從網路取得資料時,通常會先取得 JSON 字串,再解
Android MediaPlayer 多媒體播放實作指南
在 Android 開發中,音訊與影片播放是常見需求。Android 內建的 MediaPlayer 類別提供了一個直接可用的播放服務,可處理本機資源、檔案路徑或串流來源
Android 教學:依系列圖片繪製動畫的三種做法
本文要說明如何依據一系列圖片來繪製動畫。根據素材的不同,主要可以分成三種做法,以下逐一介紹。一、使用系統提供的 Animation 類這種方式最簡單,用自帶的方法即可。其