編輯:關於 Android 程式設計
最近在做一款電商 B 端 App,新版本上線後終於有時間停下來梳理代碼。今天想聊的是自定義 View 裡最容易被低估的一類——組合控件。它不是為了炫技去重寫 onDraw,而是把「一坨重複的 XML」封裝成一個可複用的組件。

要實現的是後面那三塊卡片。它們結構幾乎一樣:一張封面圖 + 標題 + 價格區。如果一個一個用 XML 硬寫,不僅工作量大,還會讓布局文件變得臃腫難讀。
更好的做法是:把「一塊」做成自定義 View,需要的時候 include 或直接寫標籤引入。代碼簡潔,後續改動也只改一處。
LinearLayout 做縱向排列;android:layout_weight 控制比例,這樣不同屏幕下比例都穩定;LinearLayout,設 android:gravity="center" 居中;先把 XML 寫好,這是組合 View 的核心——視覺結構用聲明式描述,代碼只負責邏輯:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/recommended_item_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/item_bound"
android:clickable="true"
android:orientation="vertical">
<com.personal.views.RemoteImageView
android:id="@+id/recommended_item_front_cover"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="2.5"
android:scaleType="centerCrop"
android:src="@drawable/default_loading" />
<!-- 標題與價格區省略 -->
</LinearLayout>
然後新建 Java 類繼承 LinearLayout,把布局加載進來:
public class RecommendedItem extends LinearLayout {
public static final String TAG = RecommendedItem.class.getSimpleName();
private Context mContext;
private boolean isDataSet = false;
private float titleTextSize, newPriceTextSize, oldPriceTextSize;
private RemoteImageView mItemCover;
private TextView mItemTitle, mItemNewPrice, mItemOldPrice;
private LinearLayout mPriceLayout, mRootLayout;
public RecommendedItem(Context context) {
super(context);
init(context, null);
}
public RecommendedItem(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
@SuppressLint("NewApi")
public RecommendedItem(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
mContext = context;
LayoutInflater.from(context).inflate(R.layout.v2_recommended_item, this, true);
}
}
三個構造函數都要寫,因為系統會根據不同場景(代碼 new、XML 反射、帶默認樣式)調用不同的一個。inflate(..., this, true) 的最後一個參數是 attachToRoot,傳 true 表示把加載的布局直接掛到當前 ViewGroup 上。
在 values 下新建 attrs.xml:
<declare-styleable name="RecommendedItem">
<attr name="title_textsize" format="dimension" />
<attr name="newPrice_textsize" format="dimension" />
<attr name="oldPrice_textsize" format="dimension" />
</declare-styleable>
在 init() 中取出這些值:
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RecommendedItem);
this.titleTextSize = array.getDimension(R.styleable.RecommendedItem_title_textsize, 15);
this.newPriceTextSize = array.getDimension(R.styleable.RecommendedItem_newPrice_textsize, 15);
this.oldPriceTextSize = array.getDimension(R.styleable.RecommendedItem_oldPrice_textsize, 12);
array.recycle(); // 必須調用,否則會影響後續的屬性讀取
recycle() 這一步經常被遺漏。TypedArray 內部持有的是共享的資源池對象,不歸還會導致後面的控件拿到髒數據,這是一個非常隱蔽的 bug。
@Override
protected void onFinishInflate() {
super.onFinishInflate();
this.mItemCover = (RemoteImageView) findViewById(R.id.recommended_item_front_cover);
this.mItemTitle = (TextView) findViewById(R.id.recommended_item_title);
this.mItemNewPrice = (TextView) findViewById(R.id.recommended_item_newprice);
this.mItemOldPrice = (TextView) findViewById(R.id.recommended_item_oldprice);
this.mPriceLayout = (LinearLayout) findViewById(R.id.recommended_item_price_layout);
this.mRootLayout = (LinearLayout) findViewById(R.id.recommended_item_root);
this.mItemTitle.setTextSize(this.titleTextSize);
this.mItemNewPrice.setTextSize(this.newPriceTextSize);
this.mItemOldPrice.setTextSize(this.oldPriceTextSize);
}
為什麼不用 init()?因為 inflate() 只是把 View 對象創建出來,子 View 的 onFinishInflate() 完成後整個樹才算就緒。放在這裡能保證 findViewById 一定能找到。
封裝的意義在於「內部複雜、外部簡單」。所以我們提供一組語義清晰的 setter:
// 點擊事件
public void setOnClickListener(OnClickListener listener) {
if (listener != null) {
this.mRootLayout.setOnClickListener(listener);
}
}
// 封面圖:支持資源 id / URL / Bitmap 三種來源
public void setItemCover(int resId) {
this.mItemCover.setImageResource(resId);
}
public void setItemCover(String url) {
this.mItemCover.setImageUrl(url);
}
public void loadItemCover(String remoteUrl) {
UILManager.displayImage(remoteUrl, this.mItemCover, UILManager.optionsPicsPreview);
}
// 標題
public void setItemTitle(String title) {
this.mItemTitle.setText(title);
}
public String getItemTitle() {
if (!TextUtils.isEmpty(this.mItemTitle.getText())) {
return this.mItemTitle.getText().toString();
}
return null;
}
// 價格:舊價加刪除線
public void setItemNewPrice(String newPrice) {
this.mItemNewPrice.setText(String.format(
mContext.getString(R.string.recommended_item_price_format), newPrice));
}
public void setItemOldPrice(String oldPrice) {
this.mItemOldPrice.setText(String.format(
mContext.getString(R.string.recommended_item_price_format), oldPrice));
this.mItemOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
}
// 價格區可整體隱藏(例如未填數據時)
public void setPriceLayoutVisible(boolean visible) {
this.mPriceLayout.setVisibility(visible ? View.VISIBLE : View.GONE);
}
// 列表復用時的狀態標記
public boolean isDataSet() {
return isDataSet;
}
public void setDataSet(boolean isDataSet) {
this.isDataSet = isDataSet;
if (isDataSet && this.mPriceLayout.getVisibility() == View.GONE) {
this.mPriceLayout.setVisibility(View.VISIBLE);
}
}
// 復用前重置,避免上傳入的圖文殘留
public void clearView() {
this.mItemCover.setImageResource(R.drawable.default_loading);
this.mItemTitle.setText(null);
this.mPriceLayout.setVisibility(View.GONE);
}
clearView() 這類方法在 ListView / RecyclerView 場景下是必須的。Adapter 的 getView() 裡傳入的 convertView 是複用的,如果不主動重置,就會出現「圖片串行」「價格殘留」這類經典 bug。
<com.personal.views.RecommendedItem
android:id="@+id/recommended_spike_1"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_marginLeft="10dip"
android:layout_weight="1" />
在代碼中直接拿來用即可:
RecommendedItem item = (RecommendedItem) findViewById(R.id.recommended_spike_1);
item.setItemCover("https://example.com/a.jpg");
item.setItemTitle("商品標題");
item.setItemNewPrice("99");
item.setItemOldPrice("199");

組合 View 的價值不在代碼量,而在「把重複結構收斂成一處」。判斷是否該封裝的標準很簡單:同一段布局出現第三次以上,就該動手了。相比自定義 ViewGroup 去重寫 onMeasure / onLayout,組合 View 幾乎沒有學習成本,卻能解決大多數「重複卡片」問題。
版本控制入門實戰:SVN 與 Git 的安裝、操作與衝突處理
版本控制這件事,一個人寫玩具專案時感覺不出價值,團隊協作第一天就會明白它為什麼不能少。這篇把 SVN 與 Git 兩套工具從安裝到實戰走一遍,當成課堂筆記的整理。 一、
layout_weight 是怎麼分配剩餘空間的
效果 程式碼 <LinearLayout xmlns:android=https://schemas.android.com/apk/res/android
動手寫一個 Android 桌面滑動切換螢幕的控件(二)
上一篇把骨架、測量、佈局與觸控都搭好了,這篇來補上剩下幾個關鍵環節:動畫驅動、效能優化、跨頁預繪製,以及底部指示點。 一、對頁動畫的起點 在 ViewGroup 中實
Android 多媒體框架(二十三):MediaCodec 軟硬解之辨與 MediaMuxer 實戰剪輯視頻
前幾章一直在啃 MediaCodec 的源碼,收到不少提問:MediaCodec 到底是硬解碼還是軟解碼?這個問題值得單獨說清楚。今天的主題包括:MediaCodec 的