編輯:關於 Android 程式設計
翻開現在的手機應用,你幾乎一定會遇到這樣一種設計:屏幕底部整齊地排列著一排 Tab 標籤,手指輕點其中任意一個,主區域的內容就隨之切換到對應的頁面。這正是音樂、社交、新聞類應用的標配交互,例如下面這幾款應用:




仔細觀察會發現,底部這四個標籤各自對應著一個 Fragment。這種「底部導航 + 內容切換」的布局幾乎是移動端的通用范式。那它究竟是如何實現的呢?老一輩的 Android 開發者可能脫口而出:用 TabHost 不就完了?話雖如此,TabHost 其實並不好用——它擴展性極差,Tab 上顯示的內容幾乎無法自由定制,而且運行時還得依賴早已被官方廢棄的 ActivityGroup。ActivityGroup 原本的作用是為 TabHost 的每個子項管理一個獨立的 Activity,但隨著 Fragment 的誕生,這套老方案也就退出了歷史舞台。
廢話不多說,我們直接動手實現。
首先準備主布局文件。這裡以 activity_main.xml 為例,在其中寫入如下結構:
<framelayout android:id="@+id/Content" android:layout_height="0dp" android:layout_weight="1" android:layout_width="match_parent"> </framelayout>
這段代碼乍看冗長,其實可以拆成兩塊來理解。第一塊是 FrameLayout,我們只給它一個 id 命名為 Content,內部暫且不放任何具體內容,因為真正的頁面稍後會動態填充進來。第二塊是 FrameLayout 下方的 LinearLayout,它承載了整個類似 TabHost 的底部導航欄。我們用 layout_weight 把這條 LinearLayout 平均分成四份,每一份裡都放一個 ImageView 和一個 TextView——前者負責顯示 Tab 圖標,後者負責顯示 Tab 標題。如此一來,視覺效果就和 QQ 之類的應用如出一轍了。

接下來動手編寫各個 Fragment 及其布局。先新建 discover_music_fragment.xml 作為「發現音樂」頁面的界面:
這個布局的作用很直觀:在屏幕正中央擺放一個圖標和一段說明文字。

有了布局,再來寫與之配套的 Fragment。新建 DiscoverMusicFragment 並繼承 Fragment:
public class DiscoverMusicFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View discover_music_fragment = inflater.inflate( R.layout.discover_music_fragment, container, false); return discover_music_fragment; } }
其餘幾個 Fragment 的寫法完全一致,這裡就不再逐一貼出。至此,四個 Fragment 及其對應布局都已就緒,接下來是最關鍵的 MainActivity:
public class MainActivity extends Activity implements OnClickListener { /** 展示「發現音樂」的 Fragment */ private DiscoverMusicFragment discoverMusicFragment; /** 展示「我的音樂」的 Fragment */ private MyMusicFragment myMusicFragment; /** 展示「朋友」的 Fragment */ private FriendsFragment friendsFragment; /** 展示「賬號」的 Fragment */ private AccountFragment accountFragment; /** 各個 Tab 的布局容器 */ private View discover_music_layout; private View my_music_layout; private View friends_layout; private View account_layout; /** 各個 Tab 的圖標控件 */ private ImageView discover_music_image; private ImageView my_music_image; private ImageView friends_image; private ImageView account_image; /** 各個 Tab 的標題控件 */ private TextView discover_music_text; private TextView my_music_text; private TextView friends_text; private TextView account_text; /** 用於管理 Fragment */ private FragmentManager fragmentManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); // 初始化布局元素 initViews(); fragmentManager = getFragmentManager(); // 首次啟動時默認選中第 0 個 Tab setTabSelection(0); } private void initViews() { // 四個布局 discover_music_layout = findViewById(R.id.discover_layout); my_music_layout = findViewById(R.id.my_layout); friends_layout = findViewById(R.id.friends_layout); account_layout = findViewById(R.id.account_layout); // 四個圖標 discover_music_image = (ImageView) findViewById(R.id.discover_image); my_music_image = (ImageView) findViewById(R.id.my_image); friends_image = (ImageView) findViewById(R.id.friends_image); account_image = (ImageView) findViewById(R.id.account_image); // 四個標題 discover_music_text = (TextView) findViewById(R.id.discover_text); my_music_text = (TextView) findViewById(R.id.my_text); friends_text = (TextView) findViewById(R.id.friends_text); account_text = (TextView) findViewById(R.id.account_text); // 綁定點擊事件 discover_music_layout.setOnClickListener(this); my_music_layout.setOnClickListener(this); friends_layout.setOnClickListener(this); account_layout.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.discover_layout: setTabSelection(0); break; case R.id.my_layout: setTabSelection(1); break; case R.id.friends_layout: setTabSelection(2); break; case R.id.account_layout: setTabSelection(3); break; default: break; } } /** 根據傳入的 index 設置選中的 Tab 頁。 0=發現音樂,1=我的音樂,2=朋友,3=賬號 */ private void setTabSelection(int index) { // 先清除上一次的選中狀態 clearSelection(); // 開啟一個 Fragment 事務 FragmentTransaction fragmentTransaction = fragmentManager .beginTransaction(); // 先隱藏所有 Fragment,避免同時出現多個界面 HideFragments(fragmentTransaction); switch (index) { case 0: discover_music_text.setTextColor(Color.BLUE); if (discoverMusicFragment == null) { discoverMusicFragment = new DiscoverMusicFragment(); fragmentTransaction.add(R.id.Content, discoverMusicFragment); } else { fragmentTransaction.show(discoverMusicFragment); } break; case 1: my_music_text.setTextColor(Color.BLUE); if (myMusicFragment == null) { myMusicFragment = new MyMusicFragment(); fragmentTransaction.add(R.id.Content, myMusicFragment); } else { fragmentTransaction.show(myMusicFragment); } break; case 2: friends_text.setTextColor(Color.BLUE); if (friendsFragment == null) { friendsFragment = new FriendsFragment(); fragmentTransaction.add(R.id.Content, friendsFragment); } else { fragmentTransaction.show(friendsFragment); } break; case 3: account_text.setTextColor(Color.BLUE); if (accountFragment == null) { accountFragment = new AccountFragment(); fragmentTransaction.add(R.id.Content, accountFragment); } else { fragmentTransaction.show(accountFragment); } break; default: break; } fragmentTransaction.commit(); } /** 將所有 Fragment 設為隱藏 */ private void HideFragments(FragmentTransaction fragmentTransaction) { if (discoverMusicFragment != null) { fragmentTransaction.hide(discoverMusicFragment); } if (myMusicFragment != null) { fragmentTransaction.hide(myMusicFragment); } if (friendsFragment != null) { fragmentTransaction.hide(friendsFragment); } if (accountFragment != null) { fragmentTransaction.hide(accountFragment); } } /** 清除所有選中狀態 */ private void clearSelection() { discover_music_text.setTextColor(Color.parseColor("#82858b")); my_music_text.setTextColor(Color.parseColor("#82858b")); friends_text.setTextColor(Color.parseColor("#82858b")); account_text.setTextColor(Color.parseColor("#82858b")); } }
如果一時看不明白,可以對照代碼裡的註釋慢慢消化。下面我把整體思路再梳理一遍。
在 onCreate() 中,先調用 initViews() 拿到所有控件的實例並綁定點擊監聽,然後調用 setTabSelection() 設定默認選中項——傳入 0 表示默認選中第一個 Tab。
setTabSelection() 的處理邏輯是這樣的:第一步調用 clearSelection() 把之前的選中狀態還原;接著開啟 Fragment 事務,並先隱藏所有已存在的 Fragment,防止界面疊加;然後根據 index 判斷選中的是哪個 Tab,切換該 Tab 的文字顏色,再把對應的 Fragment 呈現出來。這裡有個容易忽略的細節:添加 Fragment 時我們刻意沒有使用 replace(),而是先判斷 Fragment 是否為空——為空就 new 一個並 add() 進來,不為空就直接 show() 顯示。
為什麼不用 replace()?因為 replace() 會把被替換的 Fragment 徹底移除,它的生命周期也就隨之結束。等你下次再點回這個 Tab 時,Fragment 的生命周期會從頭再走一遍,onCreate()、onCreateView() 等方法全部重新執行,這顯然是我們不希望看到的,也不符合當初 ActivityGroup 的設計初衷。所以最佳做法是採用 hide() 和 show() 來切換,既省去了重建開銷,又能保住 Fragment 的狀態。
設好默認選中項後,用戶點擊任意 Tab 便會進入 onClick()。這裡的判斷非常簡單:點哪個標籤就調用 setTabSelection() 傳入對應的參數,一切都交給同一個方法統一處理。
至此,全部代碼就完成了,趕快去動手跑一跑吧!順帶一提,這個布局在橫屏下同樣能正常顯示。今天的分享就到這裡,有任何疑問歡迎在下方留言,感謝閱讀!
Intellij IDEA + Android SDK + Genymotion:打造順手的 Android 開發環境
長期用 Eclipse 開發 Android,也曾試過 Android Studio,各種 IDE 搭配 SDK 與原生模擬器的滋味大概大家都領略過:Eclipse 的啟
Android Dialog 使用大全:五種常見對話框一次學會
對話框是與使用者確認、選擇、輸入資訊時最直接的互動元件。Android 的 AlertDialog.Builder 提供了足夠的彈性,從簡單提示到完全自訂版面都能勝任。
Android NDK 學習筆記十:JNI 域與方法描述符速查
在使用 JNI 與 Java 層交互時,我們往往需要獲取域 ID 或方法 ID,而這一步的前提,是先寫出正確的域描述符與方法描述符。 好消息是,無論是域描述符還是方法描述
Java / Android 設計模式筆記(5):對象池模式 Object Pool
為什麼需要對象池 在 Java 與 Android 開發中,有些物件建立成本很高,但使用時間很短,而且可能會被頻繁建立與回收。若每次都重新 new 一個物件,再交由 GC