編輯:關於 Android 程式設計
Android 內建的 LinearLayout、RelativeLayout、FrameLayout 能滿足大部分需求,但遇到界面要求較複雜、需要層疊錯位排列的場景,這幾個佈局就會顯得捉襟見肘。所以自定義 ViewGroup 在成熟應用中幾乎無所不在。
實現自定義 ViewGroup 的第一步是學會自定義屬性,這能讓佈局檔的配置更靈活。做法是在 values 目錄下建立 attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CascadeViewGroup">
<attr name="verticalspacing" format="dimension"/>
<attr name="horizontalspacing" format="dimension"/>
</declare-styleable>
<declare-styleable name="CascadeViewGroup_LayoutParams">
<attr name="layout_paddingleft" format="dimension"/>
<attr name="layout_paddinTop" format="dimension"/>
</declare-styleable>
</resources>
這裡宣告了兩組屬性集:CascadeViewGroup 中的屬性作用在 ViewGroup 標籤本身,控制子 View 之間的水平與垂直間距;CascadeViewGroup_LayoutParams 則作用在每個子 View 上,允許單獨指定偏移量。
接著在 dimens.xml 中定義默認間距,作為使用者未指定時的 fallback:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="default_horizontal_spacing">10dp</dimen>
<dimen name="default_vertical_spacing">10dp</dimen>
</resources>
package com.app.CustomViewMotion;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by charles on 2015/8/13.
*/
public class CascadeViewGroup extends ViewGroup {
//自定義佈局中設置的水平與垂直間距
private int mHoriztonalSpacing;
private int mVerticalSpacing;
public CascadeViewGroup(Context context) {
this(context, null);
}
public CascadeViewGroup(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CascadeViewGroup(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CascadeViewGroup);
try {
//獲取設置的間距
mHoriztonalSpacing = a.getDimensionPixelSize(
R.styleable.CascadeViewGroup_horizontalspacing,
this.getResources().getDimensionPixelSize(R.dimen.default_horizontal_spacing));
mVerticalSpacing = a.getDimensionPixelSize(
R.styleable.CascadeViewGroup_verticalspacing,
this.getResources().getDimensionPixelSize(R.dimen.default_vertical_spacing));
} catch (Exception e) {
e.printStackTrace();
} finally {
a.recycle();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int count = this.getChildCount();
int width = this.getPaddingLeft();
int height = this.getPaddingTop();
for (int i = 0; i < count; i++) {
final View currentView = this.getChildAt(i);
this.measureChild(currentView, widthMeasureSpec, heightMeasureSpec);
CascadeViewGroup.LayoutParams lp =
(CascadeViewGroup.LayoutParams) currentView.getLayoutParams();
if (lp.mSettingPaddingLeft != 0) {
width += lp.mSettingPaddingLeft;
}
if (lp.mSettingPaddingTop != 0) {
height += lp.mSettingPaddingTop;
}
//把當前子 View 的目標座標記在 LayoutParams 中
lp.x = width;
lp.y = height;
width += mHoriztonalSpacing;
height += mVerticalSpacing;
}
width += getChildAt(this.getChildCount() - 1).getMeasuredWidth()
+ this.getPaddingRight();
height += getChildAt(this.getChildCount() - 1).getMeasuredHeight()
+ this.getPaddingBottom();
this.setMeasuredDimension(resolveSize(width, widthMeasureSpec),
resolveSize(height, heightMeasureSpec));
}
@Override
protected void onLayout(boolean b, int l, int i1, int i2, int i3) {
final int count = this.getChildCount();
for (int i = 0; i < count; i++) {
final View currentView = this.getChildAt(i);
CascadeViewGroup.LayoutParams lp =
(CascadeViewGroup.LayoutParams) currentView.getLayoutParams();
currentView.layout(lp.x, lp.y,
lp.x + currentView.getMeasuredWidth(),
lp.y + currentView.getMeasuredHeight());
}
}
/** 自定義 LayoutParams,用來承載每個子 View 的偏移與最終座標 */
public static class LayoutParams extends ViewGroup.LayoutParams {
int x;
int y;
int mSettingPaddingLeft;
int mSettingPaddingTop;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
TypedArray a = c.obtainStyledAttributes(
attrs, R.styleable.CascadeViewGroup_LayoutParams);
mSettingPaddingLeft = a.getDimensionPixelSize(
R.styleable.CascadeViewGroup_LayoutParams_layout_paddingleft, 0);
mSettingPaddingTop = a.getDimensionPixelSize(
R.styleable.CascadeViewGroup_LayoutParams_layout_paddinTop, 0);
a.recycle();
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return new LayoutParams(p);
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(this.getContext(), attrs);
}
}
代碼稍長,但結構很清晰,可以拆成五個環節來理解:
1)構造方法中讀取屬性。透過 TypedArray 取得 XML 中設置的值,存進成員變量。
2)自定義內部類 LayoutParams。用它在測量階段暫存子 View 的屬性與計算出的座標,留給 layout 階段使用。
3)重寫 generateLayoutParams 系列方法。必須返回自定義的 LayoutParams,否則 getLayoutParams() 轉型時會出錯。想了解原因,翻一下 ViewGroup.addView() 的源碼就很清楚了。
4)measure 階段。先測量自己的尺寸,同時逐個測量子 View,並把位置資訊寫進 LayoutParams。
5)layout 階段。依據 LayoutParams 中记录的 x、y 依次擺放各子 View。
<?xml version="1.0" encoding="utf-8"?>
<!--添加自定義屬性給 viewGroup-->
<!--新添加的命名空間的後綴必須保持和 .xml 中聲明的包名一致-->
<com.app.CustomViewMotion.CascadeViewGroup
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:ts="https://schemas.android.com/apk/res/com.app.CustomViewMotion"
android:layout_width="match_parent"
android:layout_height="match_parent"
ts:horizontalspacing="15dp"
ts:verticalspacing="15dp">
<TextView
android:layout_width="100dp"
android:layout_height="100dp"
android:gravity="center"
android:text="text1"
android:background="#668B8B"/>
<TextView
android:layout_width="100dp"
android:layout_height="100dp"
android:gravity="center"
android:text="text2"
android:background="#FFDAB9"/>
<TextView
android:layout_width="100dp"
android:layout_height="100dp"
android:gravity="center"
android:text="text3"
android:background="#43CD80"/>
<!--這個子 view 中添加自定義子 view 屬性-->
<TextView
android:layout_width="100dp"
android:layout_height="100dp"
android:gravity="center"
android:text="text4"
ts:layout_paddingleft="100dp"
ts:layout_paddinTop="100dp"
android:background="#00CED1"/>
</com.app.CustomViewMotion.CascadeViewGroup>
效果如下,第四個子 View 因為設定了額外偏移而錯位層疊:

這裡有個細節值得留意:命名空間的後綴必須與清單檔中聲明的包名完全一致,否則自定義屬性會解析失敗。這是自定義 ViewGroup 初學時最常見的報錯來源之一。
Android 依賴注入:Dagger 實例講解(以「煮咖啡」為例)
Dagger 是 Android / Java 平台的依賴注入框架,由專注於行動支付的公司 Square 推出。這家公司也貢獻了許多 Android 開發常用庫:Otto
Android 開發筆記:廣播接收器 BroadcastReceiver 完全指南
一、廣播接收器是什麼 BroadcastReceiver 是 Android 四大組件之一,可以把它理解成一個掛在系統層級上的「全局監聽器」。它本身不開界面、不長駐進程,
Android 基礎全攻略:JSON 資料的解析與封裝一站式掌握
本文涵蓋以下內容:JSON 是什麼、JSONObject 的解析與存儲、JSONObject 的解析與存儲(抽象)、JSONArray 的解析與存儲,以及模擬周邊加油站
Android 自定義帶標題邊框 Layout 實作指南
前言在 Android 開發中,系統內建的 TextView、LinearLayout 等元件雖然使用方便,但當產品需要更特殊的視覺呈現時,自定義 View 就成為必備技