編輯:關於 Android 程式設計
手上只有一份固定尺寸的美工設計圖,卻要同時適配幾百種屏幕,這是 Android 開發的常分之一。本文記錄一套以「設計稿尺寸」為基準、在執行期計算縮放比例並用程式碼套用尺寸的做法,適合大量使用絕對像素排版的老專案改造。
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); Display d = windowManager.getDefaultDisplay(); mWidth = d.getWidth(); mHeight = d.getHeight(); DisplayMetrics dm = getResources().getDisplayMetrics(); mScreenDensity = dm.density;
這裡同時取寬高與 density。前者是像素數,後者是 dp 與 px 的換算係數,後面計算文字大小時會用到。
把設計稿的寬高存成常數,例如 uiWidth、uiHeight(常見如 720×1280)。這是一切的基準。
float scaleWidth = mWidth / uiWidth; float scaleHeight = mHeight / uiHeight;
public static int getWidthSize(int size) {
return (int) (size * scaleWidth);
}
public static int getHightSize(int size) {
return (int) (size * scaleHeight);
}
public static float getTextSize(int pxSize) {
return (pxSize * scaleHeight) / mScreenDensity;
}
public static void setViewSize(int width, int height, View v) {
int paramWidth = getWidthSize(width);
int paramHeight = getHightSize(height);
ViewGroup.MarginLayoutParams params =
(ViewGroup.MarginLayoutParams) v.getLayoutParams();
if (width != INVALID) {
params.width = paramWidth;
}
if (height != INVALID) {
params.height = paramHeight;
}
v.setLayoutParams(params);
}
public static void setViewPadding(int left, int top, int right, int bottom, View v) {
left = getWidthSize(left);
top = getHightSize(top);
right = getWidthSize(right);
bottom = getWidthSize(bottom);
v.setPadding(left, top, right, bottom);
}
public static void setViewMargin(int left, int top, int right, int bottom, View v) {
int paramLeft = getWidthSize(left);
int paramTop = getHightSize(top);
int paramRight = getWidthSize(right);
int paramBottom = getHightSize(bottom);
ViewGroup.MarginLayoutParams params =
(ViewGroup.MarginLayoutParams) v.getLayoutParams();
if (left != INVALID) {
params.leftMargin = paramLeft;
}
if (right != INVALID) {
params.rightMargin = paramRight;
}
if (top != INVALID) {
params.topMargin = paramTop;
}
if (bottom != INVALID) {
params.bottomMargin = paramBottom;
}
v.setLayoutParams(params);
}
這套方案的優點是改造成本低:只要把設計稿上的像素值原封不動搬進程式碼,畫面就能在各尺寸上等比還原。INVALID 這個哨兵值讓呼叫端可以只指定需要調整的邊,不必四邊全給。
缺點同樣明顯:寬高分別縮放會破壞長寬比,在極端比例(例如折疊屏或平板)上容易變形;而且所有尺寸都在執行期計算,效能與可讀性都不如在 XML 裡用 dp 加不同資源限定符來得乾淨。因此更推薦的做法仍以 wrap_content、match_parent、dp/sp 與多套 dimens 資源為主,這套縮放法留給確實無法放棄絕對排版的歷史專案。
動手寫一個 Android 文件管理器:項目資源層梳理
文件管理器是幫助用戶處理本地與網絡文件的工具,基本能力包括創建、打開、查看、編輯、移動、刪除,很多還擴展了網絡訪問、應用管理、解壓縮與搜索。動手實現一個,能把 Activ
Android DigitalClock 數位時鐘元件用法實例
本文說明 Android 內建的 DigitalClock 元件怎麼用,重點是:它完全不需要寫 Java 就能顯示時間。 直接在版面檔裡放上去就好 DigitalClo
Weex 與原生頁面互動:用 runtime 動態跳轉並傳遞參數
在混合式 App 中,Weex 頁面常需要跳轉到原生頁面。若頁面名稱與所需參數固定,直接寫死即可;但若希望通用,可讓原生提供一個動態跳轉方法,接收類別名稱與參數字典。實作
Android 仿 QQ「附近的人」雷達掃描效果完整實作
一、概述老規矩,先上圖:對照一下原版(這次就不錄 gif 了,大家可以自己在 Q 群助手開啟共享地理位置,回到群聊頁就能看到):相似度應該還算可以。觀察之後可以拆出幾個結