編輯:關於 Android 程式設計
抽屜用來承載系統中所有需要展示給用戶的應用與小部件(也可以按需過濾,把不想露出的項目隱藏),是啟動應用、添加快捷方式、卸載應用的主要入口。並非所有 Launcher 都有抽屜,例如 MIUI 就取消了這一層;Launcher3 默認保留,同時也提供了關閉抽屜的途徑。本文先把抽屜本身講透。


抽屜的布局文件是 apps_customize_pane.xml,它以 include 的方式被引入 launcher.xml:
<include android:id="@+id/apps_customize_pane"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:visibility="invisible"
layout="@layout/apps_customize_pane" />
<com.android.launcher3.AppsCustomizeTabHost
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:launcher="https://schemas.android.com/apk/res-auto"
android:clipChildren="false">
<LinearLayout
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:clipChildren="false">
<FrameLayout
android:id="@+id/fake_page_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
android:clipToPadding="false">
<FrameLayout
android:id="@+id/fake_page"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:visibility="invisible" />
<com.android.launcher3.AppsCustomizePagedView
android:id="@+id/apps_customize_pane_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
launcher:maxGap="@dimen/workspace_max_gap"
launcher:pageIndicator="@+id/apps_customize_page_indicator"
launcher:widgetCountX="@integer/apps_customize_widget_cell_count_x"
launcher:widgetCountY="@integer/apps_customize_widget_cell_count_y" />
</FrameLayout>
<include
android:id="@+id/apps_customize_page_indicator"
layout="@layout/page_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
</LinearLayout>
</com.android.launcher3.AppsCustomizeTabHost>
這就是抽屜的樹形結構:AppsCustomizeTabHost 是根視圖,id/content 是內容區,內含一個 FrameLayout 與頁面指示器 indicator。而這個 FrameLayout 又分兩塊,上層 fake_page 是動畫用的過渡頁,下層 AppsCustomizePagedView 才是真正渲染應用列表與小部件的核心。
首先要澄清一個誤解:並不是點擊抽屜按鈕後才開始加載數據。此前分析 Launcher3 加載流程時已經知道,數據在 Launcher 啟動階段就完成了加載。道理也很好理解,系統裡裝了幾十上百個應用,若每次打開抽屜都重新掃描一遍,體驗會非常糟糕。
這部分對應 loadAndBindAllApps 流程,它會把應用信息寫入數據庫並綁定到 AppsCustomizePagedView。所以進入抽屜時要做的,僅僅是把內容顯示出來並把 Workspace 隱藏掉。
進入抽屜有兩個入口:點擊桌面的抽屜按鈕,或長按桌面選擇小部件。兩者進入的是同一個界面,只是加載的內容類型不同,這裡以應用列表為例。
public void onClick(View v) {
...
else if (v == mAllAppsButton) { // 抽屜按鈕
onClickAllAppsButton(v);
} else if (tag instanceof AppInfo) { // 應用列表中的應用
...
}
}
protected void onClickAllAppsButton(View v) {
if (LOGD) Log.d(TAG, "onClickAllAppsButton");
if (isAllAppsVisible()) {
showWorkspace(true);
} else {
showAllApps(true, AppsCustomizePagedView.ContentType.Applications, false);
}
if (mLauncherCallbacks != null) {
mLauncherCallbacks.onClickAllAppsButton(v);
}
}
這裡按抽屜可見性判斷顯示 Workspace 還是抽屜,但實踐中抽屜頁面並不展示抽屜按鈕,因此 showWorkspace 分支基本不會走到。直接看 showAllApps:
void showAllApps(boolean animated,
AppsCustomizePagedView.ContentType contentType,
boolean resetPageToZero) {
if (mState != State.WORKSPACE) return;
if (resetPageToZero) { // 是否需要回到首頁
mAppsCustomizeTabHost.reset();
}
showAppsCustomizeHelper(animated, false, contentType);
mAppsCustomizeTabHost.post(new Runnable() {
@Override
public void run() {
// 防止 All Apps 視圖尚未構造完成
mAppsCustomizeTabHost.requestFocus();
}
});
// 必須在所有過渡代碼執行之後再更新狀態
mState = State.APPS_CUSTOMIZE;
// 離開 All Apps 之前暫停 widget 自動輪播
mUserPresent = false;
updateRunning();
closeFolder();
getWindow().getDecorView()
.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
}
裡面調用的 showAppsCustomizeHelper 是顯示抽屜的輔助方法,與之對應的 hideAppsCustomizeHelper 用於隱藏,兩者實現高度相似,這裡只拆解顯示的部分。
方法開頭先重置上一次的動畫集合:
if (mStateAnimation != null) {
mStateAnimation.setDuration(0);
mStateAnimation.cancel();
mStateAnimation = null;
}
接著收集動畫所需的各項參數。material 變量用於判斷系統版本,Android L 及以上採用了 material design,高版本可以有更細緻的動畫表現:
boolean material = Utilities.isLmpOrAbove(); // SDK 是否 >= 21 final Resources res = getResources(); final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime); final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime); final int revealDuration = res.getInteger(R.integer.config_appsCustomizeRevealTime); final int itemsAlphaStagger = res.getInteger(R.integer.config_appsCustomizeItemsAlphaStagger); final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor); final View fromView = mWorkspace; final AppsCustomizeTabHost toView = mAppsCustomizeTabHost; final ArrayList<View> layerViews = new ArrayList<View>(); // DragLayer 上的 View
然後指定切換時的 Workspace 狀態與加載內容類型:
Workspace.State workspaceState = contentType == AppsCustomizePagedView.ContentType.Widgets
? Workspace.State.OVERVIEW_HIDDEN : Workspace.State.NORMAL_HIDDEN;
Animator workspaceAnim = mWorkspace.getChangeStateAnimation(workspaceState, animated, layerViews);
if (!LauncherAppState.isDisableAllApps()
|| contentType == AppsCustomizePagedView.ContentType.Widgets) {
mAppsCustomizeTabHost.setContentTypeImmediate(contentType);
}
boolean initialized = getAllAppsButton() != null; // 視圖是否初始化完成
只有 animated && initialized 同時成立時才播放動畫,否則直接顯示,雖然顯得突兀,但也比崩潰好。
mStateAnimation = LauncherAnimUtils.createAnimatorSet();
final AppsCustomizePagedView content =
(AppsCustomizePagedView) toView.findViewById(R.id.apps_customize_pane_content);
final View page = content.getPageAt(content.getCurrentPage()); // 抽屜當前頁
final View revealView = toView.findViewById(R.id.fake_page); // 過渡頁
final boolean isWidgetTray = contentType == AppsCustomizePagedView.ContentType.Widgets;
if (isWidgetTray) {
revealView.setBackground(res.getDrawable(R.drawable.quantum_panel_dark));
} else {
revealView.setBackground(res.getDrawable(R.drawable.quantum_panel));
}
revealView 就是前面提到的過渡頁,動畫期間頂替真實頁面,結束後隱藏。接下來把透明度與偏移量先歸零,再算出動畫的初始值:
// 先隱藏真實頁面背景,換上假背景
content.setPageBackgroundsVisible(false);
revealView.setVisibility(View.VISIBLE);
revealView.setAlpha(0f);
int width = revealView.getMeasuredWidth();
int height = revealView.getMeasuredHeight();
float revealRadius = (float) Math.sqrt((width * width) / 4 + (height * height) / 4);
revealView.setTranslationY(0);
revealView.setTranslationX(0);
// 計算頁面中心與 All Apps 按鈕中心之間的 Y 軸差值
int[] allAppsToPanelDelta =
Utilities.getCenterDeltaInScreenSpace(revealView, getAllAppsButton(), null);
float alpha = 0;
float xDrift = 0;
float yDrift = 0;
if (material) {
alpha = isWidgetTray ? 0.3f : 1f;
yDrift = isWidgetTray ? height / 2 : allAppsToPanelDelta[1];
xDrift = isWidgetTray ? 0 : allAppsToPanelDelta[0];
} else {
yDrift = 2 * height / 3;
xDrift = 0;
}
final float initAlpha = alpha;
過渡頁的組合動畫由透明度與位移共同構成,並開啟硬件層以優化性能:
revealView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
layerViews.add(revealView);
PropertyValuesHolder panelAlpha = PropertyValuesHolder.ofFloat("alpha", initAlpha, 1f);
PropertyValuesHolder panelDriftY = PropertyValuesHolder.ofFloat("translationY", yDrift, 0);
PropertyValuesHolder panelDriftX = PropertyValuesHolder.ofFloat("translationX", xDrift, 0);
ObjectAnimator panelAlphaAndDrift =
ObjectAnimator.ofPropertyValuesHolder(revealView, panelAlpha, panelDriftY, panelDriftX);
panelAlphaAndDrift.setDuration(revealDuration);
panelAlphaAndDrift.setInterpolator(new LogDecelerateInterpolator(100, 0));
mStateAnimation.play(panelAlphaAndDrift);
當前頁的動畫同理,也是屬性動畫,只是多了個 itemsAlphaStagger 的起始延遲,讓元素依次淡入:
if (page != null) {
page.setVisibility(View.VISIBLE);
page.setLayerType(View.LAYER_TYPE_HARDWARE, null);
layerViews.add(page);
ObjectAnimator pageDrift = ObjectAnimator.ofFloat(page, "translationY", yDrift, 0);
page.setTranslationY(yDrift);
pageDrift.setDuration(revealDuration);
pageDrift.setInterpolator(new LogDecelerateInterpolator(100, 0));
pageDrift.setStartDelay(itemsAlphaStagger);
mStateAnimation.play(pageDrift);
page.setAlpha(0f);
ObjectAnimator itemsAlpha = ObjectAnimator.ofFloat(page, "alpha", 0f, 1f);
itemsAlpha.setDuration(revealDuration);
itemsAlpha.setInterpolator(new AccelerateInterpolator(1.5f));
itemsAlpha.setStartDelay(itemsAlphaStagger);
mStateAnimation.play(itemsAlpha);
}
動畫監聽裡負責收尾:
mStateAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
dispatchOnLauncherTransitionEnd(fromView, animated, false);
dispatchOnLauncherTransitionEnd(toView, animated, false);
revealView.setVisibility(View.INVISIBLE); // 隱藏過渡頁
revealView.setLayerType(View.LAYER_TYPE_NONE, null);
if (page != null) {
page.setLayerType(View.LAYER_TYPE_NONE, null);
}
content.setPageBackgroundsVisible(true); // 顯示抽屜內容
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.hideSearchBar(false); // 隱藏搜索欄
}
mStateAnimation = null;
}
});
if (workspaceAnim != null) {
mStateAnimation.play(workspaceAnim);
}
Workspace 的動畫定義在 Workspace.java 的 getChangeStateAnimation 中,覆蓋了桌面到縮略圖、縮略圖到桌面、桌面到抽屜等多種場景,本質上都是 alpha 與 scale 的組合。
最後用一個 Runnable 觸發播放,並在 L 以上版本提前 buildLayer:
final Runnable startAnimRunnable = new Runnable() {
public void run() {
if (mStateAnimation != stateAnimation) return;
dispatchOnLauncherTransitionStart(fromView, animated, false);
dispatchOnLauncherTransitionStart(toView, animated, false);
revealView.setAlpha(initAlpha);
if (Utilities.isLmpOrAbove()) {
for (int i = 0; i < layerViews.size(); i++) {
View v = layerViews.get(i);
if (v != null && Utilities.isViewAttachedToWindow(v)) v.buildLayer();
}
}
mStateAnimation.start();
}
};
方法中反覆調用的 dispatchOnLauncherTransitionXXX,最終會走到實現了 LauncherTransitionable 接口的 View 裡,在切換的不同階段各自做處理:
interface LauncherTransitionable {
View getContent();
void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace);
void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace);
void onLauncherTransitionStep(Launcher l, float t);
void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace);
}
Launcher3 抽屜的默認背景是白色,想改成透明該怎麼做?直覺上會去布局文件裡找 AppsCustomizePagedView 並設置透明背景,但這樣改是沒有效果的。
<com.android.launcher3.AppsCustomizePagedView
android:id="@+id/apps_customize_pane_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
launcher:maxGap="@dimen/workspace_max_gap"
launcher:pageIndicator="@+id/apps_customize_page_indicator"
launcher:widgetCountX="@integer/apps_customize_widget_cell_count_x"
launcher:widgetCountY="@integer/apps_customize_widget_cell_count_y" />
原因在於 AppsCustomizePagedView 內部還有一層 AppsCustomizeCellLayout,每一頁就是一個 CellLayout。真正的背景是在 setupPage 中設上去的,位於 launcher3\src\main\java\com\android\launcher3\AppsCustomizePagedView.java:
private void setupPage(AppsCustomizeCellLayout layout) {
layout.setGridSize(mCellCountX, mCellCountY);
// 這裡強制 measure,避免同步後緊接着做布局計算時拿不到正確寬度
setVisibilityOnChildren(layout, View.GONE);
int widthSpec = MeasureSpec.makeMeasureSpec(mContentWidth, MeasureSpec.AT_MOST);
int heightSpec = MeasureSpec.makeMeasureSpec(mContentHeight, MeasureSpec.AT_MOST);
layout.measure(widthSpec, heightSpec);
// 設置 page 背景色
Drawable bg = getContext().getResources().getDrawable(R.drawable.quantum_panel);
if (bg != null) {
bg.setAlpha(mPageBackgroundsVisible ? 255 : 0);
layout.setBackground(bg);
}
setVisibilityOnChildren(layout, View.VISIBLE);
}
把這段換成透明背景即可:
layout.setBackgroundColor(Color.TRANSPARENT);
背景透明之後,灰色的應用名稱會顯得不太協調,改成白色更合適。文字顏色在 syncAppsPageItems 方法中統一設置:
for (int i = startIndex; i < endIndex; ++i) {
AppInfo info = mApps.get(i);
BubbleTextView icon = (BubbleTextView) mLayoutInflater
.inflate(R.layout.apps_customize_application, layout, false);
icon.applyFromApplicationInfo(info);
icon.setOnClickListener(mLauncher);
icon.setOnLongClickListener(this);
icon.setOnTouchListener(this);
icon.setOnKeyListener(this);
icon.setOnFocusChangeListener(layout.mFocusHandlerView);
icon.setTextColor(Color.WHITE);
...
}
布局文件裡通過 launcher:widgetCountX 與 launcher:widgetCountY 控制的是小部件的展示數量,之所以能這樣寫,是因為 AppsCustomizePagedView 中聲明了這兩個屬性:
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0); mWidgetCountX = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountX, 2); mWidgetCountY = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountY, 2);
但應用列表並沒有對應屬性,所以要弄清行列數從何而來。mCellCountX 與 mCellCountY 分別代表列數與行數,賦值發生在 onDataReady 中:
protected void onDataReady(int width, int height) {
LauncherAppState app = LauncherAppState.getInstance();
DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
mCellCountX = (int) grid.allAppsNumCols;
mCellCountY = (int) grid.allAppsNumRows;
...
}
追溯到 DeviceProfile.java 的 updateIconSize,可以看到計算邏輯:
allAppsCellWidthPx = allAppsIconSizePx;
allAppsCellHeightPx = allAppsIconSizePx + drawablePadding + iconTextSizePx;
int maxLongEdgeCellCount = resources.getInteger(R.integer.config_dynamic_grid_max_long_edge_cell_count);
int maxShortEdgeCellCount = resources.getInteger(R.integer.config_dynamic_grid_max_short_edge_cell_count);
int minEdgeCellCount = resources.getInteger(R.integer.config_dynamic_grid_min_edge_cell_count);
int maxRows = (isLandscape ? maxShortEdgeCellCount : maxLongEdgeCellCount);
int maxCols = (isLandscape ? maxLongEdgeCellCount : maxShortEdgeCellCount);
if (allAppsShortEdgeCount > 0 && allAppsLongEdgeCount > 0) {
allAppsNumRows = isLandscape ? allAppsShortEdgeCount : allAppsLongEdgeCount;
allAppsNumCols = isLandscape ? allAppsLongEdgeCount : allAppsShortEdgeCount;
} else {
allAppsNumRows = (availableHeightPx - pageIndicatorHeightPx) / (allAppsCellHeightPx + allAppsCellPaddingPx);
allAppsNumRows = Math.max(minEdgeCellCount, Math.min(maxRows, allAppsNumRows));
allAppsNumCols = (availableWidthPx) / (allAppsCellWidthPx + allAppsCellPaddingPx);
allAppsNumCols = Math.max(minEdgeCellCount, Math.min(maxCols, allAppsNumCols));
}
結論很明確:行列數不是寫死的,而是由配置的上下限、圖標尺寸、單元間距共同推算得出。想增加數量就縮小圖標或加大可用空間,反之則減少。
Launcher3 會依機型加載不同配置,見 DynamicGrid.java:
deviceProfiles.add(new DeviceProfile("Nexus 4", 335, 567, 4, 4,
DEFAULT_ICON_SIZE_DP, 13, (hasAA ? 5 : 5), 56, R.xml.default_workspace_4x4));
deviceProfiles.add(new DeviceProfile("Nexus 5", 359, 567, 4, 4,
DEFAULT_ICON_SIZE_DP, 13, (hasAA ? 5 : 5), 56, R.xml.default_workspace_4x4));
十個參數依次為:設備名、最小寬度 Dps、最小高度 Dps、行數、列數、圖標大小、圖標字體大小、固定熱鍵數目(Hotseat)、熱鍵圖標大小、默認 Workspace 布局。
先把列數從 4 改成 5:
deviceProfiles.add(new DeviceProfile("Nexus 4", 335, 567, 4, 5,
DEFAULT_ICON_SIZE_DP, 13, (hasAA ? 5 : 5), 56, R.xml.default_workspace_4x4));
單改這一項往往看不出變化,需要同時把圖標改小,默認 60 改為 48:
static float DEFAULT_ICON_SIZE_DP = 48;
此時確實變成了 5 列,但行數也漲到了 6 行。把 config.xml 中的最大行數從 6 調回 5:
<!-- launcher3\src\main\res\values\config.xml --> <integer name="config_dynamic_grid_max_long_edge_cell_count">5</integer>
這樣就得到了 5 行 5 列。不過視覺上並不協調,我的測試機其實還是 5×4 更合適,這裡主要是說明改造的切入點在哪裡。除背景與行列數外,抽屜的動畫效果同樣可以按需替換,限於篇幅不再展開。
Android Studio個性化設置實記:背景、快捷鍵與工具欄
用Eclipse完成上一個專案之後,我決定全面轉向Android Studio 2.0。剛上手時,為了讓編碼更順手,主要做了三方面的設置: 1、修改代碼區的背景顏色;2、
告別命令行:Android Studio 項目提交與更新到 GitHub 保姆級教程
用 Android Studio 開發到一定階段,總會想把項目推到 GitHub 上留個備份或者做開源。以前只能靠 cmd 敲命令,其實 Studio 自帶的 Git 集
讀書筆記:Android LayoutInflater.inflate 參數與源碼解析
LayoutInflater 是 Android 將 XML 版面轉成 View 物件的核心類別。本文從取得實例、inflate 多載關係,到 attachToRoot
Android SQLite 與 SQL 基礎:從建表到增刪改查
SQLite 的定位 SQLite 是 Android 中常見的輕量級資料庫,適合儲存設定、小型結構化資料與本地快取。它本質上是一個檔案,不需要啟動服務,使用 SQL 語