Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

ActionBar 與 Fragment 實戰——打造仿知乎抽屜式主頁

編輯:關於 Android 程式設計

前面幾篇介紹了 Google 對 ActionBar 與 Fragment 的說明與建議用法。本篇就來動手做個範例,以「知乎」App 的主介面為靈感,示範 ActionBar 搭配 DrawerLayout 與 Fragment 的實務應用。

Fragment 自 Android 3.0 才出現,若要支援 3.0 以下版本需引入 Support Library。本專案最低支援 API Level 8,因此也會使用到 Support Library。

身為有企圖心的 Android 開發者,我們希望專案設計符合 Android Design 官方設計準則。觀察「知乎」App 的設計後,可以發現它使用了 ActionBar 與 DrawerLayout,抽屜中的項目切換對應的正是 Fragment。以下就以此為範本。

建立專案

新建 FakeZhihu 專案:

使用新版 ADT 建立專案時,若 Minimum Required SDK 設為 8 而 Target SDK 更高,系統會自動導入 Support v4;精靈最後一步選擇 Navigation Drawer,ADT 會自動產生 DrawerLayout 範例程式碼,並導入 Support v7 appcompat 以相容到 Android 2.2。

自訂 ActionBar 主題與樣式

Android 預設的 Holo 主題只有兩種色調,而「知乎」的 ActionBar 無論是顏色、action item 顏色或標題字級都是自訂的。首先開啟 res 目錄下的 style 檔,定義自訂主題並引用自訂 ActionBar 樣式:

<resources> <style name="CustomActionBarTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar"> <item name="android:actionBarStyle">@style/MyActionBar</item> <item name="actionBarStyle">@style/MyActionBar</item> </style> <style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse"> <item name="android:background">@drawable/actionbar_background</item> <item name="android:titleTextStyle">@style/MyTitleStyle</item> <item name="background">@drawable/actionbar_background</item> <item name="titleTextStyle">@style/MyTitleStyle</item> </style> <style name="MyTitleStyle" parent="@android:style/TextAppearance.Holo.Widget.ActionBar.Title.Inverse"> <item name="android:textSize">20dp</item> </style> </resources>

重點:無論自訂主題或樣式,都要視情況加上 parent 屬性,否則無法沿用父樣式中未被覆蓋的設定。

套用主題

完成後記得在 manifest 套用,可讓整個應用或單一 Activity 使用自訂主題:

<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.sweetvvck.fakezhihu" android:versionCode="1" android:versionName="1.0"> <application android:theme="@style/CustomActionBarTheme"> </application> </manifest>

加入 DrawerLayout

修改 MainActivity 版面,加入 DrawerLayout,其中包含一個 Drawer 與內容容器:

<FrameLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:id="@+id/navigation_drawer" android:layout_width="@dimen/navigation_drawer_width" android:layout_height="match_parent" android:layout_gravity="start" android:name="com.sweetvvck.fakezhihu.NavigationDrawerFragment" /> </FrameLayout>

其中 android:layout_gravity 表示抽屜從哪一側劃出,start 為左側、end 為右側;也可定義左右兩個 fragment。

抽屜 Fragment 的資料

為抽屜定義一個包含 ListView 的 Fragment,第一項與其他項樣式不同,可用 headerView 實作。使用字串陣列存放標題:

<string-array name="item_title"> <item>首頁</item> <item>發現</item> <item>關注</item> <item>收藏</item> <item>草稿</item> <item>搜索</item> <item>提問</item> <item>設置</item> </string-array>
String[] itemTitle = getResources().getStringArray(R.array.item_title); int[] itemIconRes = { R.drawable.ic_drawer_home, R.drawable.ic_drawer_explore, R.drawable.ic_drawer_follow, R.drawable.ic_drawer_collect, R.drawable.ic_drawer_draft, R.drawable.ic_drawer_search, R.drawable.ic_drawer_question, R.drawable.ic_drawer_setting}; for (int i = 0; i < itemTitle.length; i++) { DrawerListItem item = new DrawerListItem(getResources().getDrawable(itemIconRes[i]), itemTitle[i]); mData.add(item); }

單選高亮效果

要讓 ListView 為單選模式並在選中時高亮,有兩個步驟:其一,設定 android:choiceMode=singleChoice;其二,為 item 背景、圖片 src 與文字顏色設定對應 activated 狀態的 selector。

item 背景:

<selector xmlns:android="https://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/activated_background_color" android:state_activated="true" /> <item android:drawable="@android:color/transparent" /> </selector>

圖片 src(以 home 為例):

<selector xmlns:android="https://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/ic_drawer_home_pressed" android:state_activated="true" /> <item android:drawable="@drawable/ic_drawer_home_normal" /> </selector>

文字顏色:

<selector xmlns:android="https://schemas.android.com/apk/res/android"> <item android:color="#ff999999" android:state_enabled="false" /> <item android:color="@android:color/white" android:state_activated="true" /> <item android:color="#636363" /> </selector>

首次啟動顯示抽屜

考量初次使用者可能不知道有抽屜,這是實務專案常用手法,可在首次啟動時讓抽屜展開,之後預設隱藏,以 SharedPreferences 記錄:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

Fragment 與 Activity 通訊

抽屜 Fragment 需與宿主 Activity 通訊,定義回呼介面並於宿主實作:

public static interface NavigationDrawerCallbacks { void onNavigationDrawerItemSelected(String title); }
@Override public void onNavigationDrawerItemSelected(String title) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction ft = fragmentManager.beginTransaction(); currentFragment = fragmentManager.findFragmentByTag(title); if(currentFragment == null) { currentFragment = ContentFragment.newInstance(title); ft.add(R.id.container, currentFragment, title); } if(lastFragment != null) { ft.hide(lastFragment); } if(currentFragment.isDetached()){ ft.attach(currentFragment); } ft.show(currentFragment); lastFragment = currentFragment; ft.commit(); onSectionAttached(title); }

完整的 NavigationDrawerFragment 實作如下:

package com.sweetvvck.fakezhihu; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.Fragment; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; public class NavigationDrawerFragment extends Fragment { private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position"; private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned"; private NavigationDrawerCallbacks mCallbacks; private ActionBarDrawerToggle mDrawerToggle; private DrawerLayout mDrawerLayout; private ListView mDrawerListView; private View mFragmentContainerView; private int mCurrentSelectedPosition = 0; private boolean mFromSavedInstanceState; private boolean mUserLearnedDrawer; private List mData = new ArrayList(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false); if (savedInstanceState != null) { mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION); mFromSavedInstanceState = true; } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); } public boolean isDrawerOpen() { return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView); } public void setUp(int fragmentId, DrawerLayout drawerLayout) { mFragmentContainerView = getActivity().findViewById(fragmentId); mDrawerLayout = drawerLayout; mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); actionBar.setDisplayShowHomeEnabled(false); mDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, R.drawable.ic_drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close) { @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); if (!isAdded()) { return; } getActivity().supportInvalidateOptionsMenu(); } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); if (!isAdded()) { return; } if (!mUserLearnedDrawer) { mUserLearnedDrawer = true; SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).commit(); } getActivity().supportInvalidateOptionsMenu(); } }; if (!mUserLearnedDrawer && !mFromSavedInstanceState) { mDrawerLayout.openDrawer(mFragmentContainerView); } mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); mDrawerLayout.setDrawerListener(mDrawerToggle); } private void selectItem(int position) { mCurrentSelectedPosition = position; if (mDrawerListView != null) { mDrawerListView.setItemChecked(position, true); } if (mDrawerLayout != null) { mDrawerLayout.closeDrawer(mFragmentContainerView); } if (mCallbacks != null) { if(mCurrentSelectedPosition == 0) { mCallbacks.onNavigationDrawerItemSelected(getString(R.string.app_name)); return; } mCallbacks.onNavigationDrawerItemSelected(mData.get(position - 1).getTitle()); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallbacks = (NavigationDrawerCallbacks) activity; } catch (ClassCastException e) { throw new ClassCastException("Activity must implement NavigationDrawerCallbacks."); } } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { if (mDrawerLayout != null && isDrawerOpen()) { inflater.inflate(R.menu.global, menu); showGlobalContextActionBar(); } super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } if (item.getItemId() == R.id.action_example) { Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show(); return true; } return super.onOptionsItemSelected(item); } private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setTitle(R.string.app_name); } private ActionBar getActionBar() { return ((ActionBarActivity) getActivity()).getSupportActionBar(); } public static interface NavigationDrawerCallbacks { void onNavigationDrawerItemSelected(String title); } }

完成後即可看到仿知乎的主介面:

Demo 下載:https://download.csdn.net/detail/sweetvvck/7794083

此外,抽屜開合時 ActionBar 上的 action item 會不同、如何隱藏 logo、以及如何用 add/hide/show 搭配快取已載入的 Fragment 等進階技巧,將於後續文章詳述。

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