編輯:關於 Android 程式設計
本文從 ViewGroup/View 的繪製流程談起,說明自訂 ViewGroup 的兩種常見寫法,最後整理出三種動態改變 View 位置的實作方式,並比較其優劣。
簡化來看,一個 View 從無到有要經過三個階段:onMeasure(測量大小)、onLayout(決定位置)、onDraw(實際繪製)。ViewGroup 在 onMeasure 與 onLayout 過程中會遍歷每一個子 View,最終呼叫子 View 的 measure() 與 layout()。與 View 不同的是,ViewGroup 沒有 onDraw,而是走 dispatchDraw(),由它呼叫 drawChild() 逐一觸發子 View 的 onDraw。
onMeasure 的目的在取得控件的寬高,這裡有兩個容易混淆的概念:getWidth() 是「寬度」,getMeasuredWidth() 是「測量寬度」。一般自訂的 ViewGroup(例如繼承 RelativeLayout)通常會進兩次 onMeasure、一次 onLayout、一次 drawChild()。值得注意的是,直到第二次 onMeasure 結束前,getWidth() 拿到的仍是 0,只有在 onSizeChanged() 之後才能取得正確數值,此後在 onLayout 中自然也讀得到。
下面這段程式碼示範了在 onMeasure 前後印出各種數值:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.i(TAG, "onMeasure enter...");
Log.i(TAG, "width = " + getWidth() + " height = " + getHeight());
Log.i(TAG, "MeasuredWidth = " + getMeasuredWidth() + " MeasuredHeight = " + getMeasuredHeight());
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.i(TAG, "00000000000 width = " + getWidth() + " height = " + getHeight());
Log.i(TAG, "00000000000 MeasuredWidth = " + getMeasuredWidth() + " MeasuredHeight = " + getMeasuredHeight());
Log.i(TAG, "onMeasure exit...");
}
輸出的日誌大致如下:
01-03 10:15:40.526 I/YanZi (10793): onMeasure enter... 01-03 10:15:40.526 I/YanZi (10793): width = 0 height = 0 01-03 10:15:40.527 I/YanZi (10793): MeasuredWidth = 0 MeasuredHeight = 0 01-03 10:15:40.532 I/YanZi (10793): 00000000000 width = 0 height = 0 01-03 10:15:40.532 I/YanZi (10793): 00000000000 MeasuredWidth = 1080 MeasuredHeight = 1701 01-03 10:15:40.532 I/YanZi (10793): onMeasure exit... 01-03 10:15:40.532 I/YanZi (10793): onMeasure enter... 01-03 10:15:40.533 I/YanZi (10793): width = 0 height = 0 01-03 10:15:40.533 I/YanZi (10793): MeasuredWidth = 1080 MeasuredHeight = 1701 01-03 10:15:40.537 I/YanZi (10793): onSizeChanged enter... 01-03 10:15:40.538 I/YanZi (10793): width = 1080 height = 1701 01-03 10:15:40.538 I/YanZi (10793): onLayout enter... 01-03 10:15:40.540 I/YanZi (10793): onLayout exit...
可以清楚看到,第一次進入 onMeasure 並執行完 super.onMeasure() 之後,MeasuredWidth 與 MeasuredHeight 就已經有值了。
至於為什麼要進兩次 onMeasure,網路上有幾種說法:有人認為是尺寸變化時(例如 LinearLayout 設了 weight)需要二次測量,也有人說是子 View 無法填滿父容器時才會再進一次。但我實測時,把 LinearLayout 中所有母與子的 View 尺寸全部寫死,onMeasure 一樣進兩次;改成全部 match_parent,仍然進兩次。這部分我沒有找到完全站得住腳的解釋。
實務上還有一個技巧:直接在 onMeasure 中呼叫 setMeasuredDimension(measuredWidth, measuredHeight),那麼不管 XML 裡怎麼寫,最終都以此處設定的寬高來配置與顯示。
先看配置檔 c_nanshi_guide.xml,裡面完全沒有任何自訂 View 的標籤:
<?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" >
<FrameLayout
android:id="@+id/guide_nan_layout"
android:layout_width="200dp"
android:layout_height="150dp"
android:background="@drawable/nan1" >
<TextView
android:id="@+id/guide_nan_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:gravity="center"
android:text="南公懷瑾."
android:textColor="@android:color/white"
android:textSize="20sp" />
</FrameLayout>
</RelativeLayout>
核心在於 initView() 裡用 LayoutInflater 把配置檔 inflate 進來:
public class NanShiGuide extends BaseGuideView {
private static final String TAG = "YanZi";
int LAYOUT_ID = R.layout.c_nanshi_guide;
View guideNanLayout;
TextView guideNanText;
private Drawable mDrawable;
private Context mContext = null;
public NanShiGuide(Context context, GuideViewCallback callback) {
super(context, callback);
mContext = context;
initView();
mDrawable = context.getResources().getDrawable(R.drawable.ong);
}
@Override
protected void initView() {
View v = LayoutInflater.from(mContext).inflate(LAYOUT_ID, this, true);
guideNanLayout = v.findViewById(R.id.guide_nan_layout);
guideNanText = (TextView) v.findViewById(R.id.guide_nan_text);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int transX = 0;
int transY = 0;
if (mOrientation == 0) {
guideNanLayout.setRotation(0);
} else if (mOrientation == 270) {
guideNanLayout.setRotation(90);
transX += -DisplayUtil.dip2px(mContext, 25) + DisplayUtil.dip2px(mContext, 210);
transY += DisplayUtil.dip2px(mContext, 25);
} else if (mOrientation == 180) {
guideNanLayout.setRotation(180);
transX += DisplayUtil.dip2px(mContext, 160);
transY += b - DisplayUtil.dip2px(mContext, 150);
} else if (mOrientation == 90) {
guideNanLayout.setRotation(270);
transX += -DisplayUtil.dip2px(mContext, 25);
transY += b - DisplayUtil.dip2px(mContext, 200 - 25);
}
guideNanLayout.setTranslationX(transX);
guideNanLayout.setTranslationY(transY);
super.onLayout(changed, l, t, r, b);
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
int w = getWidth();
int h = getHeight();
Point centerPoint = new Point(w / 2, h / 2);
canvas.save();
mDrawable.setBounds(centerPoint.x - 150, centerPoint.y - 150,
centerPoint.x + 150, centerPoint.y + 150);
mDrawable.draw(canvas);
canvas.restore();
return super.drawChild(canvas, child, drawingTime);
}
}
基類 BaseGuideView 負責封裝方向與點擊事件:
public abstract class BaseGuideView extends RelativeLayout implements Rotatable, View.OnClickListener {
protected int mOrientation = 0;
protected Context mContext;
private GuideViewCallback mGuideViewCallback;
public interface GuideViewCallback {
void onGuideViewClick();
}
public BaseGuideView(Context context, GuideViewCallback callback) {
super(context);
mContext = context;
mGuideViewCallback = callback;
setOnClickListener(this);
mOrientation = OrientationUtil.getOrientation();
}
@Override
public void setOrientation(int orientation, boolean animation) {
mOrientation = orientation;
requestLayout();
}
protected abstract void initView();
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
@Override
public void onClick(View v) {
mGuideViewCallback.onGuideViewClick();
}
}
這種寫法的好處是雙向相容:既可以用 Java 語句 new 出來再 addView 加入母配置,也可以直接在 XML 裡以 <org.yanzi.ui.NanShiGuide> 的方式使用。動態添加的示例如下:
if (baseGuideView == null) {
baseGuideView = new NanShiGuide(getApplicationContext(), new GuideViewCallback() {
@Override
public void onGuideViewClick() {
hideGuideView();
}
});
guideLayout.addView(baseGuideView);
}
這種寫法把 View 交給 XML 的 inflate 機制去實例化,因此建構子只能是標準的兩參數形式:
public NanShiGuide(Context context, AttributeSet attrs) {
super(context, attrs);
}
缺點很明顯:無法額外傳入重要變數,也不適合動態添加(不能 new),只能透過母配置中的 include 引入。因為它是從配置檔載入的,所以會觸發 onFinishInflate(),此時才能放心實例化子 View;而方法一不會走這個流程,必須靠 LayoutInflater。
綜合來看,我強烈建議用第一種方式自訂 ViewGroup,不過 Google 的部分原生應用採用的正是第二種。另外,兩者的載入機制不同,後續動態改位置時行為也會有差異。
我最推薦第三種,方法一在特定場合也好用,方法二則比較雞肋。
先看一下自然狀態,圖片貼齊左上角擺放:
下圖是呼叫 setRotation() 旋轉 90 度之後的樣子,guideNanLayout 就是圖片所在的配置節點。
設 View 的寬為 W、高為 H。旋轉 90 度後,圖片在 x 軸與 y 軸上各自「塌縮」了 Abs(W - H) / 2 個像素。因此第一步要把這個塌縮補回來,讓旋轉後的 View 仍以左上角為基準點,接著再用位移語法搬到你想要的位置:
guideNanLayout.setTranslationX(transX); guideNanLayout.setTranslationY(transY);
最終的 onLayout 實作如下:
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int transX = 0;
int transY = 0;
if (mOrientation == 0) {
guideNanLayout.setRotation(0);
} else if (mOrientation == 270) {
guideNanLayout.setRotation(90);
transX += -DisplayUtil.dip2px(mContext, 25) + DisplayUtil.dip2px(mContext, 210);
transY += DisplayUtil.dip2px(mContext, 25);
} else if (mOrientation == 180) {
guideNanLayout.setRotation(180);
transX += DisplayUtil.dip2px(mContext, 160);
transY += b - DisplayUtil.dip2px(mContext, 150);
} else if (mOrientation == 90) {
guideNanLayout.setRotation(270);
transX += -DisplayUtil.dip2px(mContext, 25);
transY += b - DisplayUtil.dip2px(mContext, 200 - 25);
}
guideNanLayout.setTranslationX(transX);
guideNanLayout.setTranslationY(transY);
super.onLayout(changed, l, t, r, b);
}
旋轉後的最終效果如下:
這裡我刻意沒有採用 Android 自帶的「配置旋轉」機制,因為動畫轉換太慢、效果不理想。由於位移是在 onLayout 中設定,而 onLayout 發生在 onDraw 之前,所以方向切換時不會出現殘影;即使一開機就橫拿手機,也不會先顯示直式再轉過去。
每次方向改變時,只需更新角度並呼叫 requestLayout():
@Override
public void setOrientation(int orientation, boolean animation) {
mOrientation = orientation;
requestLayout();
}
那為什麼不用 setX()?看它的原始碼就知道答案:
/**
* Sets the visual x position of this view, in pixels. This is equivalent to setting the
* translationX property to be the difference between the x value passed in and the
* current left property.
*/
public void setX(float x) {
setTranslationX(x - mLeft);
}
setX 最終仍舊是呼叫 setTranslationX,那不如直接用後者。在本例中把 setTranslationX/Y 換成 setX/Y 結果一模一樣,只因為此處 mLeft 恰好等於 0。
再回頭看方法一。透過 LayoutParams 改位置有兩個明顯問題:其一,View 必須先載入完成才拿得到 LayoutParams;其二,一旦 rotate 之後 margin 的計算變得相當棘手。更麻煩的是,在本例的 onLayout 裡設定子 View 的 margin 完全看不到效果,但同樣的程式碼放到 initView 或 onMeasure 裡卻正常運作。我的推論是:等到母配置的 onLayout 階段才去改子 View 的 margin 已經太晚,margin 必須在 onLayout 之前設定好。
另外要注意,在 onLayout 裡未加前綴的 setX 等同於 this.setX(),作用對象是母配置本身;要操作子 View 必須先取得該子 View 的參照。而且位移只要放在 super.onLayout() 之前設定即可,不需要去改動那五個參數。
從 setLayoutParams 的實作也能看出問題所在:
public void setLayoutParams(ViewGroup.LayoutParams params) {
if (params == null) {
throw new NullPointerException("Layout parameters cannot be null");
}
mLayoutParams = params;
resolveLayoutParams();
if (mParent instanceof ViewGroup) {
((ViewGroup) mParent).onSetLayoutParams(this, params);
}
requestLayout();
}
設定參數後最終呼叫的是 requestLayout(),也就是要求自己重新走一遍 measure 與 layout,效率自然較差;而在母配置的 onLayout 裡呼叫 setTranslateX 並不會額外增加流程。至於為何第二種自訂寫法反而能在 onLayout 中靠 margin 動態配置子 View,我認為是兩者的載入機制差異所致,這部分尚無定論。
方向角可以透過 OrientationEventListener 取得,並經過平滑處理後再通知 View 更新:
mOrientationEvent = new OrientationEventListener(this) {
@Override
public void onOrientationChanged(int orientation) {
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
return;
}
mOrientation = RoundUtil.roundOrientation(orientation, mOrientation);
int orientationCompensation =
(mOrientation + RoundUtil.getDisplayRotation(MainActivity.this)) % 360;
if (mOrientationCompensation != orientationCompensation) {
mOrientationCompensation = orientationCompensation;
OrientationUtil.setOrientation(mOrientationCompensation == -1 ? 0 : mOrientationCompensation);
setOrientation(OrientationUtil.getOrientation(), false);
}
}
};
@Override
protected void onResume() {
super.onResume();
mOrientationEvent.enable();
}
@Override
protected void onPause() {
super.onPause();
mOrientationEvent.disable();
}
角度平滑與取得系統旋轉值的工具類:
public class RoundUtil {
public static final int ORIENTATION_HYSTERESIS = 5;
public static int roundOrientation(int orientation, int orientationHistory) {
boolean changeOrientation = false;
if (orientationHistory == OrientationEventListener.ORIENTATION_UNKNOWN) {
changeOrientation = true;
} else {
int dist = Math.abs(orientation - orientationHistory);
dist = Math.min(dist, 360 - dist);
changeOrientation = (dist >= 45 + ORIENTATION_HYSTERESIS);
}
if (changeOrientation) {
return ((orientation + 45) / 90 * 90) % 360;
}
return orientationHistory;
}
public static int getDisplayRotation(Activity activity) {
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
switch (rotation) {
case Surface.ROTATION_0: return 0;
case Surface.ROTATION_90: return 90;
case Surface.ROTATION_180: return 180;
case Surface.ROTATION_270: return 270;
}
return 0;
}
}
這套取角度的做法只在角度變化達到門檻時才通知更新,比直接監聽原始值嚴謹得多。
最後補充一個關鍵結論:View 呼叫 rotate() 時,無論怎麼轉都是繞著自身中心點旋轉。只要母配置沒有旋轉,座標系原點就固定是螢幕左上角,且 x、y 軸不會互換。
原始碼下載:https://download.csdn.net/detail/yanzi1225627/7681731
自定義錄音動畫 View:聲波跳動、倒數計時與環形進度一次搞定
需求與成品 專案裡要做一个按住說話的錄音元件,附帶剩餘時間倒數、外圈進度條,還有一段會隨音量起伏的模擬聲波。時間壓得很緊,於是直接自己畫一個 View 把它整體繪製出來。
Android UI 開發利器 Angrytools 工具集合介紹
對於個人開發者或小型團隊而言,UI 設計往往是一個痛點。沒有專業美工支持時,開發者可以借助一些在線工具快速生成界面元素,提升應用整體觀感。Angrytools 的定位An
Android AIDL 跨進程通訊:呼叫遠端服務的完整流程
Android AIDL 跨進程通訊 Android 中每個 App 通常運行於獨立進程。若需要讓不同進程之間互相呼叫方法或傳遞資料,可使用 AIDL。AIDL 會依介面
非 ROOT 靜默安裝的實現思路與實踐:AIDL、反射 ServiceManager 與系統簽名
最近公司的自研系統要做一個升級服務,包含三大功能:一是系統升級,即下載 OTA 包推送到 recovery 中完成升級;二是 MCU 升級,這涉及我們自家系統的具體情況;