編輯:Android 開發實例
如今 Fragment 的應用可謂越來越廣泛。當初 Android 在 3.0 引入 Fragment,主要是為了解決平板屏幕較大、空間利用不充分的問題;而現在即便只是手機,也有越來越多的場景能發揮 Fragment 的所長。今天我們就來學一個特別實用的技巧。
很多手機應用都有這麼一個相似的功能:屏幕下方顯示一行 Tab 標簽,點擊不同標簽就能切換到不同界面。比如下面幾個應用就是典型代表。
從左到右依次是 QQ、新浪微博和支付寶錢包,可見這種底部標簽式的布局策略真的非常常見。
那這種效果該怎麼實現?熟悉 Android 的朋友一定脫口而出:用 TabHost 不就完了!殊不知 TabHost 並沒那麼簡單,它可擴展性很差,不能隨意定制 Tab 項顯示的內容,而且運行還依賴於 ActivityGroup。ActivityGroup 原本主要用於為每個 TabHost 子項管理一個單獨的 Activity,但如今已被廢棄——原因就是 Fragment 的出現!查看官方文檔對 ActivityGroup 的描述可以看到,早在 API 13 時 Android 就將其廢棄,並推薦用更靈活的 Fragment 來替代。
那剩下的問題就是:如何借助 Fragment 完成類似 TabHost 的效果?這就動手吧。
開始之前,你必須已經了解 Fragment 的用法。如果還比較陌生,建議先讀我前面的一篇文章:https://www.fengfly.com/plus/view-215089-1.html。
另外,我們還要準備好程序所需資源,比如每個 Tab 項用到的圖片。這裡我提前從 QQ 裡截了幾張圖作為項目資源,稍後會連同源碼一併給出。
新建項目 FragmentDemo,這裡我使用 4.0 的 API。
首先編寫一個類似 QQ 的主界面,當然只寫最下方的 TabHost 部分,上面的內容界面不寫——因為內容界面應該寫在 Fragment 的布局裡。打開或新建 activity_main.xml,加入如下代碼:
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <FrameLayout
- android:id="@+id/content"
- android:layout_width="match_parent"
- android:layout_height="0dp"
- android:layout_weight="1" >
- </FrameLayout>
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="60dp"
- android:background="@drawable/tab_bg" >
- <RelativeLayout
- android:id="@+id/message_layout"
- android:layout_width="0dp"
- android:layout_height="match_parent"
- android:layout_weight="1" >
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_centerVertical="true"
- android:orientation="vertical" >
- <ImageView
- android:id="@+id/message_image"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:src="@drawable/message_unselected" />
- <TextView
- android:id="@+id/message_text"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:text="消息"
- android:textColor="#82858b" />
- </LinearLayout>
- </RelativeLayout>
- <RelativeLayout
- android:id="@+id/contacts_layout"
- android:layout_width="0dp"
- android:layout_height="match_parent"
- android:layout_weight="1" >
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_centerVertical="true"
- android:orientation="vertical" >
- <ImageView
- android:id="@+id/contacts_image"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:src="@drawable/contacts_unselected" />
- <TextView
- android:id="@+id/contacts_text"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:text="聯系人"
- android:textColor="#82858b" />
- </LinearLayout>
- </RelativeLayout>
- <RelativeLayout
- android:id="@+id/news_layout"
- android:layout_width="0dp"
- android:layout_height="match_parent"
- android:layout_weight="1" >
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_centerVertical="true"
- android:orientation="vertical" >
- <ImageView
- android:id="@+id/news_image"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:src="@drawable/news_unselected" />
- <TextView
- android:id="@+id/news_text"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:text="動態"
- android:textColor="#82858b" />
- </LinearLayout>
- </RelativeLayout>
- <RelativeLayout
- android:id="@+id/setting_layout"
- android:layout_width="0dp"
- android:layout_height="match_parent"
- android:layout_weight="1" >
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_centerVertical="true"
- android:orientation="vertical" >
- <ImageView
- android:id="@+id/setting_image"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:src="@drawable/setting_unselected" />
- <TextView
- android:id="@+id/setting_text"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:text="設置"
- android:textColor="#82858b" />
- </LinearLayout>
- </RelativeLayout>
- </LinearLayout>
- </LinearLayout>
這段布局雖長,其實主要分兩部分。第一部分是 FrameLayout,這裡只把它的 id 設為 content,不添加任何具體內容,因為內容要在後面動態加進來。第二部分是它下面的 LinearLayout,也就是整個類似 TabHost 的布局。可以看到,這個 LinearLayout 又被等分成四份,每份顯示一個 ImageView 和一個 TextView:ImageView 顯示 Tab 圖標,TextView 顯示 Tab 標題,效果便和 QQ 非常接近。
既然等分了四份,接下來自然要分別實現四個 Fragment 及其布局。新建 message_layout.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" >
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerInParent="true"
- android:orientation="vertical" >
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:src="@drawable/message_selected" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:padding="10dp"
- android:text="這是消息界面"
- android:textSize="20sp" />
- </LinearLayout>
- </RelativeLayout>
這個布局就簡單多了,只是在屏幕正中央顯示一個消息圖標和一段文字。接著創建對應的 Fragment,新建 MessageFragment 繼承自 Fragment:
- public class MessageFragment extends Fragment {
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View messageLayout = inflater.inflate(R.layout.message_layout, container, false);
- return messageLayout;
- }
- }
後面就依葫蘆畫瓢,把其餘幾個 Fragment 及布局一一創建出來。新建 contacts_layout.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" >
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerInParent="true"
- android:orientation="vertical" >
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:src="@drawable/contacts_selected" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:padding="10dp"
- android:text="這是聯系人界面"
- android:textSize="20sp" />
- </LinearLayout>
- </RelativeLayout>
再新建 ContactsFragment 繼承自 Fragment:
- public class ContactsFragment extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View contactsLayout = inflater.inflate(R.layout.contacts_layout,
- container, false);
- return contactsLayout;
- }
- }
然後新建 news_layout.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" >
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerInParent="true"
- android:orientation="vertical" >
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:src="@drawable/news_selected" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:padding="10dp"
- android:text="這是動態界面"
- android:textSize="20sp" />
- </LinearLayout>
- </RelativeLayout>
再新建 NewsFragment 繼承自 Fragment:
- public class NewsFragment extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View newsLayout = inflater.inflate(R.layout.news_layout, container,
- false);
- return newsLayout;
- }
- }
最後新建 setting_layout.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" >
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerInParent="true"
- android:orientation="vertical" >
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:src="@drawable/setting_selected" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:padding="10dp"
- android:text="這是設置界面"
- android:textSize="20sp" />
- </LinearLayout>
- </RelativeLayout>
再新建 SettingFragment 繼承自 Fragment:
- public class SettingFragment extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View settingLayout = inflater.inflate(R.layout.setting_layout,
- container, false);
- return settingLayout;
- }
- }
這樣,四個 Fragment 及其布局就都建好了。接下來是最關鍵的一步——打開或新建 MainActivity 作為主 Activity:
- /**
- * 項目的主Activity,所有的Fragment都嵌入在這裡。
- *
- * @author guolin
- */
- public class MainActivity extends Activity implements OnClickListener {
- /**
- * 用於展示消息的Fragment
- */
- private MessageFragment messageFragment;
- /**
- * 用於展示聯系人的Fragment
- */
- private ContactsFragment contactsFragment;
- /**
- * 用於展示動態的Fragment
- */
- private NewsFragment newsFragment;
- /**
- * 用於展示設置的Fragment
- */
- private SettingFragment settingFragment;
- /**
- * 消息界面布局
- */
- private View messageLayout;
- /**
- * 聯系人界面布局
- */
- private View contactsLayout;
- /**
- * 動態界面布局
- */
- private View newsLayout;
- /**
- * 設置界面布局
- */
- private View settingLayout;
- /**
- * 在Tab布局上顯示消息圖標的控件
- */
- private ImageView messageImage;
- /**
- * 在Tab布局上顯示聯系人圖標的控件
- */
- private ImageView contactsImage;
- /**
- * 在Tab布局上顯示動態圖標的控件
- */
- private ImageView newsImage;
- /**
- * 在Tab布局上顯示設置圖標的控件
- */
- private ImageView settingImage;
- /**
- * 在Tab布局上顯示消息標題的控件
- */
- private TextView messageText;
- /**
- * 在Tab布局上顯示聯系人標題的控件
- */
- private TextView contactsText;
- /**
- * 在Tab布局上顯示動態標題的控件
- */
- private TextView newsText;
- /**
- * 在Tab布局上顯示設置標題的控件
- */
- private TextView settingText;
- /**
- * 用於對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() {
- messageLayout = findViewById(R.id.message_layout);
- contactsLayout = findViewById(R.id.contacts_layout);
- newsLayout = findViewById(R.id.news_layout);
- settingLayout = findViewById(R.id.setting_layout);
- messageImage = (ImageView) findViewById(R.id.message_image);
- contactsImage = (ImageView) findViewById(R.id.contacts_image);
- newsImage = (ImageView) findViewById(R.id.news_image);
- settingImage = (ImageView) findViewById(R.id.setting_image);
- messageText = (TextView) findViewById(R.id.message_text);
- contactsText = (TextView) findViewById(R.id.contacts_text);
- newsText = (TextView) findViewById(R.id.news_text);
- settingText = (TextView) findViewById(R.id.setting_text);
- messageLayout.setOnClickListener(this);
- contactsLayout.setOnClickListener(this);
- newsLayout.setOnClickListener(this);
- settingLayout.setOnClickListener(this);
- }
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.message_layout:
- // 當點擊了消息tab時,選中第1個tab
- setTabSelection(0);
- break;
- case R.id.contacts_layout:
- // 當點擊了聯系人tab時,選中第2個tab
- setTabSelection(1);
- break;
- case R.id.news_layout:
- // 當點擊了動態tab時,選中第3個tab
- setTabSelection(2);
- break;
- case R.id.setting_layout:
- // 當點擊了設置tab時,選中第4個tab
- setTabSelection(3);
- break;
- default:
- break;
- }
- }
- /**
- * 根據傳入的index參數來設置選中的tab頁。
- *
- * @param index
- * 每個tab頁對應的下標。0表示消息,1表示聯系人,2表示動態,3表示設置。
- */
- private void setTabSelection(int index) {
- // 每次選中之前先清楚掉上次的選中狀態
- clearSelection();
- // 開啟一個Fragment事務
- FragmentTransaction transaction = fragmentManager.beginTransaction();
- // 先隱藏掉所有的Fragment,以防止有多個Fragment顯示在界面上的情況
- hideFragments(transaction);
- switch (index) {
- case 0:
- // 當點擊了消息tab時,改變控件的圖片和文字顏色
- messageImage.setImageResource(R.drawable.message_selected);
- messageText.setTextColor(Color.WHITE);
- if (messageFragment == null) {
- // 如果MessageFragment為空,則創建一個並添加到界面上
- messageFragment = new MessageFragment();
- transaction.add(R.id.content, messageFragment);
- }else {
- // 如果MessageFragment不為空,則直接將它顯示出來
- transaction.show(messageFragment);
- }
- break;
- case 1:
- // 當點擊了聯系人tab時,改變控件的圖片和文字顏色
- contactsImage.setImageResource(R.drawable.contacts_selected);
- contactsText.setTextColor(Color.WHITE);
- if (contactsFragment == null) {
- // 如果ContactsFragment為空,則創建一個並添加到界面上
- contactsFragment = new ContactsFragment();
- transaction.add(R.id.content, contactsFragment);
- }else {
- // 如果ContactsFragment不為空,則直接將它顯示出來
- transaction.show(contactsFragment);
- }
- break;
- case 2:
- // 當點擊了動態tab時,改變控件的圖片和文字顏色
- newsImage.setImageResource(R.drawable.news_selected);
- newsText.setTextColor(Color.WHITE);
- if (newsFragment == null) {
- // 如果NewsFragment為空,則創建一個並添加到界面上
- newsFragment = new NewsFragment();
- transaction.add(R.id.content, newsFragment);
- }else {
- // 如果NewsFragment不為空,則直接將它顯示出來
- transaction.show(newsFragment);
- }
- break;
- case 3:
- default:
- // 當點擊了設置tab時,改變控件的圖片和文字顏色
- settingImage.setImageResource(R.drawable.setting_selected);
- settingText.setTextColor(Color.WHITE);
- if (settingFragment == null) {
- // 如果SettingFragment為空,則創建一個並添加到界面上
- settingFragment = new SettingFragment();
- transaction.add(R.id.content, settingFragment);
- }else {
- // 如果SettingFragment不為空,則直接將它顯示出來
- transaction.show(settingFragment);
- }
- break;
- }
- transaction.commit();
- }
- /**
- * 清除掉所有的選中狀態。
- */
- private void clearSelection() {
- messageImage.setImageResource(R.drawable.message_unselected);
- messageText.setTextColor(Color.parseColor("#82858b"));
- contactsImage.setImageResource(R.drawable.contacts_unselected);
- contactsText.setTextColor(Color.parseColor("#82858b"));
- newsImage.setImageResource(R.drawable.news_unselected);
- newsText.setTextColor(Color.parseColor("#82858b"));
- settingImage.setImageResource(R.drawable.setting_unselected);
- settingText.setTextColor(Color.parseColor("#82858b"));
- }
- /**
- * 將所有的Fragment都置為隱藏狀態。
- *
- * @param transaction
- * 用於對Fragment執行操作的事務
- */
- private void hideFragments(FragmentTransaction transaction) {
- if (messageFragment != null) {
- transaction.hide(messageFragment);
- }
- if (contactsFragment != null) {
- transaction.hide(contactsFragment);
- }
- if (newsFragment != null) {
- transaction.hide(newsFragment);
- }
- if (settingFragment != null) {
- transaction.hide(settingFragment);
- }
- }
- }
這個類的註釋已經寫得很詳細,我再幫大家快速梳理一遍。onCreate() 中先調用 initViews() 拿到每個控件的實例並設好點擊事件,再調用 setTabSelection() 設置默認選中項,傳入的 0 表示默認選中第 1 個 Tab。
setTabSelection() 又是如何處理的呢?第一步先調用 clearSelection() 清理上次的選中狀態,接著開啟一個 Fragment 事務並隱藏所有 Fragment,避免多個 Fragment 同時顯示。然後根據傳入的 index 判斷選中的是哪個 Tab,改變該 Tab 的圖標和文字顏色,再把相應的 Fragment 添加到界面上。這裡有個細節:添加 Fragment 時並沒有使用 replace(),而是先判斷該 Fragment 是否為空——為空則用 add() 添加,不為空則直接用 show() 顯示。為什麼不用 replace()?因為 replace() 會把被替換的 Fragment 徹底移除,其生命週期就此結束;再次點擊時又會重新走一遍 onCreate()、onCreateView() 等,這顯然不是我們想要的,也不符合 ActivityGroup 的行為。所以最好的方案是用 hide() 和 show() 來隱藏與顯示,這樣 Fragment 的生命週期就不會重走一遭。
設置好默認項後,我們還能通過點擊 Tab 自由切換界面,這便進入 onClick()。它的邏輯很簡單:點消息選第 1 個、點聯系人選第 2 個、點動態選第 3 個、點設置選第 4 個,都是調用 setTabSelection() 只是傳入不同參數。
全部代碼編寫完成,運行起來看看吧。整個 Tab 界面頗有幾分 QQ 的感覺,點擊不同 Tab 即可切換界面;即使在橫屏下也有不錯的適配性。
就這樣,我們成功用 Fragment 編寫出了和 TabHost 一樣的效果。每個界面的具體邏輯都可以寫在各自的 Fragment 裡,效果與寫在 Activity 中相差無幾。如此一來,我們終於可以和被廢棄的 ActivityGroup 說再見了!
源碼下載,請點擊這裡。
Android Canvas 繪圖透解:MaskFilter 模糊陰影與浮雕效果(附源碼)
本文聚焦一個既實用又有趣的繪圖技巧——如何借助 MaskFilter 為圖形加上模糊陰影與浮雕立體效果。先理清一個概念:Canvas 上的各種 drawXXX 方法決定了
Android 左右滑動與索引圖示效果實作
在許多圖片瀏覽或引導頁面中,常會看到左右滑動切換圖片,並在下方顯示對應索引圖示的效果。這個功能可以透過 Gallery 與 ImageView 組合完成。自訂 Galle
Android Activity 生命週期完整解析
Activity 是 Android 四大組件之一,其生命週期由系統依使用情境與資源狀態調用。理解各階段回呼,有助於正確管理資源與資料。四大基本狀態Activity 可分
封裝 SQLite 分頁表格控件 GVTable:表格區與分頁列的完整實作
前一篇談了 SQLite 的分頁讀取,但那個版本只是把資料印在文字方塊裡。這次往前一步:把「分頁 + 表格呈現」封裝成一個可重複使用的自訂控件。 執行結果: 為什