編輯:關於 Android 程式設計
從初次接觸 RN 到現在終於能寫出點東西,值得給自己一個肯定。學習這條路還長,廢話少說,直接進主題。
RN 的螢幕適配,說真的比 Android 原生簡單不少——不得不佩服 Facebook 把原生控制項封裝得如此到位。身為 Android 工程師轉做 RN,要考量的細節確實比 iOS 工程師多一些。
結合 Android 的適配經驗,我在 RN 中也封裝了一個工具類 ScreenUtils.js:
/**
* 螢幕工具類
* UI 設計基準:iPhone 6,width 750、height 1334
*/
var ReactNative = require('react-native');
var Dimensions = require('Dimensions');
export var screenW = Dimensions.get('window').width;
export var screenH = Dimensions.get('window').height;
var fontScale = ReactNative.PixelRatio.getFontScale();
export var pixelRatio = ReactNative.PixelRatio.get();
const r2 = 2;
const w2 = 750 / r2;
const h2 = 1334 / r2;
export const DEFAULT_DENSITY = 2;
/** 設定 text 為 sp,回傳 dp */
export function setSpText(size) {
var scaleWidth = screenW / w2;
var scaleHeight = screenH / h2;
var scale = Math.min(scaleWidth, scaleHeight);
size = Math.round((size * scale + 0.5) * pixelRatio / fontScale);
return size;
}
/** 螢幕適配:縮放尺寸 */
export function scaleSize(size) {
var scaleWidth = screenW / w2;
var scaleHeight = screenH / h2;
var scale = Math.min(scaleWidth, scaleHeight);
size = Math.round((size * scale + 0.5));
return size / DEFAULT_DENSITY;
}
寫過 RN 的都清楚,程式碼中直接寫的寬高單位是 dp。所以我們得先定一個美工交付的設計基準(這裡用 iPhone 6 的 750×1334),再換算成 dp。
接著取得實際裝置的螢幕寬高,算出比例,得知「設計稿上的 100px 換算到這支手機是多少 px」,最後轉成 dp 塞進 style:
const styles = StyleSheet.create({
container: {
backgroundColor: 'white',
justifyContent: 'space-between',
flexDirection: 'row',
paddingTop: ScreenUtils.scaleSize(22),
paddingBottom: ScreenUtils.scaleSize(22),
paddingRight: ScreenUtils.scaleSize(12),
paddingLeft: ScreenUtils.scaleSize(12),
alignItems: 'center'
},
});
RN 端的適配就到這裡。
原生開發時我們多半在 XML 裡寫版面,寫的時候根本無法預知會跑在哪支手機上。官方建議用 dp、多建 layout 與 values 目錄——這個做法我個人也很認同,效率高又清楚。
但除了官方路線,能不能像 RN 那樣在執行後動態算出比例再套用版面?答案是肯定的,RN 本身就是證明。而在它之前,鴻洋大神也早已對百分比版面做了完整封裝與解析。
接下來要做的事,就是在百分比版面的基礎上再封一層,讓我們可以直接寫上美工標註的 px 數值,就能適配絕大多數機型。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:context="com.example.leo.textdemo.MainActivity">
<com.yasin.px_percent_layout.PercentLinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#ff0000"
android:text="10%w, 10%h"
android:textColor="#fff"
app:layout_heightPercent="10%h"
app:layout_widthPercent="10%w" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#ffff00"
android:text="螢幕寬的 20%sw,螢幕高的 20%sh"
android:textColor="#ff0000"
app:layout_heightPercent="20%sh"
app:layout_widthPercent="20%sw" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#0000ff"
android:text="以 iPhone6 為基準:寬 200px,高 200px"
android:textColor="#fff"
app:layout_heightPercent="200px"
app:layout_widthPercent="200px" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#00ff00"
android:text="以 iPhone6 為基準:寬 375px,高 375px,textSize 28px"
android:textColor="#ff0000"
app:layout_heightPercent="375px"
app:layout_textSizePercent="28px"
app:layout_widthPercent="375px" />
</com.yasin.px_percent_layout.PercentLinearLayout>
</RelativeLayout>
public class PercentLinearLayout extends LinearLayout {
private PercentLayoutHelper mPercentLayoutHelper;
public PercentLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mPercentLayoutHelper = new PercentLayoutHelper(this);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int tmpHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int tmpWidthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode);
// 修正 ScrollView 內高度未指定的問題
if (heightMode == MeasureSpec.UNSPECIFIED
&& getParent() != null && getParent() instanceof ScrollView) {
int baseHeight = 0;
Context context = getContext();
if (context instanceof Activity) {
Activity act = (Activity) context;
baseHeight = act.findViewById(android.R.id.content).getMeasuredHeight();
} else {
baseHeight = getScreenHeight();
}
tmpHeightMeasureSpec = MeasureSpec.makeMeasureSpec(baseHeight, heightMode);
}
mPercentLayoutHelper.adjustChildren(tmpWidthMeasureSpec, tmpHeightMeasureSpec);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mPercentLayoutHelper.handleMeasuredStateTooSmall()) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
mPercentLayoutHelper.restoreOriginalParams();
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
public static class LayoutParams extends LinearLayout.LayoutParams
implements PercentLayoutHelper.PercentLayoutParams {
private PercentLayoutHelper.PercentLayoutInfo mPercentLayoutInfo;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
mPercentLayoutInfo = PercentLayoutHelper.getPercentLayoutInfo(c, attrs);
}
@Override
public PercentLayoutHelper.PercentLayoutInfo getPercentLayoutInfo() {
return mPercentLayoutInfo;
}
@Override
protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) {
PercentLayoutHelper.fetchWidthAndHeight(this, a, widthAttr, heightAttr);
}
public LayoutParams(int width, int height) { super(width, height); }
public LayoutParams(ViewGroup.LayoutParams source) { super(source); }
public LayoutParams(MarginLayoutParams source) { super(source); }
}
}
骨架其實很單純:建構時建立 helper、自訂 LayoutParams 並在其中解析屬性,核心那一句就是 adjustChildren()。整理成三步:
一、從版面檔讀出自訂屬性,如 app:layout_widthPercent="10%w"。
二、把讀到的值封裝進 PercentLayoutInfo。
三、在 onMeasure 中依這些資訊重算子控制項尺寸。
public static PercentLayoutInfo getPercentLayoutInfo(Context context, AttributeSet attrs) {
PercentLayoutInfo info = null;
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.PercentLayout_Layout);
info = setWidthAndHeightVal(array, info);
info = setMarginRelatedVal(array, info);
info = setTextSizeSupportVal(array, info);
info = setMinMaxWidthHeightRelatedVal(array, info);
info = setPaddingRelatedVal(array, info);
array.recycle();
return info;
}
private static PercentLayoutInfo setWidthAndHeightVal(TypedArray array, PercentLayoutInfo info) {
PercentLayoutInfo.PercentVal percentVal =
getPercentVal(array, R.styleable.PercentLayout_Layout_layout_widthPercent, true);
if (percentVal != null) {
info = checkForInfoExists(info);
info.widthPercent = percentVal;
}
percentVal =
getPercentVal(array, R.styleable.PercentLayout_Layout_layout_heightPercent, false);
if (percentVal != null) {
info = checkForInfoExists(info);
info.heightPercent = percentVal;
}
return info;
}
private static PercentLayoutInfo.PercentVal getPercentVal(String percentStr, boolean isOnWidth) {
if (percentStr == null) {
return null;
}
Pattern p = Pattern.compile(REGEX_PERCENT);
Matcher matcher = p.matcher(percentStr);
if (TextUtils.isEmpty(percentStr)
|| (!matcher.matches() && !percentStr.toLowerCase().endsWith("px"))) {
throw new RuntimeException(
"the value of layout_xxxPercent invalid! ==>" + percentStr);
}
String floatVal;
float percent;
int len = percentStr.length();
if (matcher.matches()) {
floatVal = matcher.group(1);
percent = Float.parseFloat(floatVal) / 100f;
} else {
floatVal = percentStr.substring(0, percentStr.indexOf("px"));
percent = Float.parseFloat(floatVal);
}
PercentLayoutInfo.PercentVal percentVal = new PercentLayoutInfo.PercentVal();
percentVal.percent = percent;
if (percentStr.endsWith(PercentLayoutInfo.BASEMODE.SW)) {
percentVal.basemode = PercentLayoutInfo.BASEMODE.BASE_SCREEN_WIDTH;
} else if (percentStr.endsWith(PercentLayoutInfo.BASEMODE.SH)) {
percentVal.basemode = PercentLayoutInfo.BASEMODE.BASE_SCREEN_HEIGHT;
} else if (percentStr.endsWith(PercentLayoutInfo.BASEMODE.PERCENT)) {
percentVal.basemode = isOnWidth
? PercentLayoutInfo.BASEMODE.BASE_WIDTH
: PercentLayoutInfo.BASEMODE.BASE_HEIGHT;
} else if (percentStr.endsWith(PercentLayoutInfo.BASEMODE.W)) {
percentVal.basemode = PercentLayoutInfo.BASEMODE.BASE_WIDTH;
} else if (percentStr.endsWith(PercentLayoutInfo.BASEMODE.H)) {
percentVal.basemode = PercentLayoutInfo.BASEMODE.BASE_HEIGHT;
} else if (percentStr.endsWith(PercentLayoutInfo.BASEMODE.PX)) {
percentVal.basemode = PercentLayoutInfo.BASEMODE.ABSOLUTE_PX;
} else {
throw new IllegalArgumentException(
"the " + percentStr + " must be endWith [%|w|h|sw|sh|px]");
}
return percentVal;
}
核心就是把字串拆開,判斷屬於哪一種基準模式:
private enum BASEMODE {
BASE_WIDTH,
BASE_HEIGHT,
BASE_SCREEN_WIDTH,
BASE_SCREEN_HEIGHT,
ABSOLUTE_PX;
public static final String PERCENT = "%"; // 父容器
public static final String W = "w"; // 父容器寬
public static final String H = "h"; // 父容器高
public static final String SW = "sw"; // 螢幕寬
public static final String SH = "sh"; // 螢幕高
public static final String PX = "px"; // 絕對像素(依設計基準換算)
}
對應到版面中寫的 10%w、20%sw、200px 等寫法,例如 20%sw 就是把 20 與 sw 分別取出封裝。
public void adjustChildren(int widthMeasureSpec, int heightMeasureSpec) {
int widthHint = View.MeasureSpec.getSize(widthMeasureSpec);
int heightHint = View.MeasureSpec.getSize(heightMeasureSpec);
for (int i = 0, N = mHost.getChildCount(); i < N; i++) {
View view = mHost.getChildAt(i);
ViewGroup.LayoutParams params = view.getLayoutParams();
if (params instanceof PercentLayoutParams) {
PercentLayoutInfo info = ((PercentLayoutParams) params).getPercentLayoutInfo();
if (info != null) {
supportTextSize(widthHint, heightHint, view, info);
supportPadding(widthHint, heightHint, view, info);
supportMinOrMaxDimesion(widthHint, heightHint, view, info);
if (params instanceof ViewGroup.MarginLayoutParams) {
info.fillMarginLayoutParams((ViewGroup.MarginLayoutParams) params,
widthHint, heightHint);
} else {
info.fillLayoutParams(params, widthHint, heightHint);
}
}
}
}
}
其中文字大小的處理最能說明設計意圖:
private void supportTextSize(int widthHint, int heightHint,
View view, PercentLayoutInfo info) {
PercentLayoutInfo.PercentVal textSizePercent = info.textSizePercent;
if (textSizePercent == null) return;
float textSize;
int base = getBaseByModeAndVal(widthHint, heightHint, textSizePercent.basemode);
if (textSizePercent.basemode == PercentLayoutInfo.BASEMODE.ABSOLUTE_PX) {
// 直接寫 px:依設計基準換算到當前裝置
textSize = ViewUtils.scaleTextValue(mHost.getContext(), textSizePercent.percent);
} else {
// 寫百分比:父容器或螢幕的寬高乘以比例
textSize = (int) (base * textSizePercent.percent);
}
// Button 與 EditText 都是 TextView 的子類
if (view instanceof TextView) {
((TextView) view).setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}
}
其餘的 padding、min/max 寬高處理邏輯大致相同,就不逐一展開。
若想直接使用 px 寫法,需要兩個前置步驟。第一,在 manifest 中宣告設計基準:
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.leo.textdemo">
<meta-data android:name="UI_WIDTH" android:value="750" />
<meta-data android:name="UI_HEIGHT" android:value="1334" />
<meta-data android:name="UI_DENSITY" android:value="2" />
<application android:name=".BaseApplication">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
第二,在 Application 中初始化:
public class BaseApplication extends Application {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
PxAppConfig.init(base);
}
}
完成後就能在版面檔中直接用 10%w、20%sh、200px、28px 這類語法。
這套做法的價值在於「照著設計稿寫數字」,溝通成本最低;代價是每個控制項都要多走一層 MeasureSpec 換算,且版面巢狀越深、子項越多,效能負擔越明顯。因此實務上我會這樣切:列表項、卡片這類大量重複且尺寸固定的元件用百分比/px 寫法;純排版容器、捲動頁面則回歸官方的 dp 加 layout qualifiers。兩者並用,比全面倒地任何一端都務實。
專案連結:https://github.com/913453448/PercentLayoutDemo
Android RocooFix 熱修復框架詳解
本文從熱修復技術的由來講起,回顧 Facebook 的 Dalvik 補丁經驗與 dex 分包方案,最後聚焦到 QQ 空間的熱補丁思路與 RocooFix 框架的實際使用
Android 入門實作:打造一個文件夾管理器(一)主體架構與列表呈現
我們手上的裝置通常都自帶廠商開發的檔案管理、相機等系統應用。今天要動手做的,是一個入門級的文件夾管理器。 整個專案大約六個類別,不摻雜任何外部服務,就是一個純粹的本地檔案
Android 使用 getDrawingCache 快速實作截圖
在 Android 中,若只需要擷取目前畫面,可以利用 View 的 Drawing Cache 機制。這種方式不需要系統截圖權限,也不依賴外部工具,適合保存表單、聊天畫
Android 記事本手寫功能:畫筆大小與顏色的設定
在記事本或手寫板類應用中,除了基本繪製,使用者通常還希望能調整筆跡粗細與顏色。這類功能可 reuse 畫板模組的設計思路,讓手寫體驗更完整。以 Paint 保存筆跡狀態手