Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

一步一步實現 Android 自定義組合 View

編輯:關於 Android 程式設計

前言

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

設計稿分析

要實現的是後面那三塊卡片。它們結構幾乎一樣:一張封面圖 + 標題 + 價格區。如果一個一個用 XML 硬寫,不僅工作量大,還會讓布局文件變得臃腫難讀。

更好的做法是:把「一塊」做成自定義 View,需要的時候 include 或直接寫標籤引入。代碼簡潔,後續改動也只改一處。

實現思路

  • 最外層用 LinearLayout 做縱向排列;
  • 圖片區和文字區用 android:layout_weight 控制比例,這樣不同屏幕下比例都穩定;
  • 文字區內部再用 LinearLayout,設 android:gravity="center" 居中;
  • 自定義屬性暴露字號、顏色等可配置項。

第一步:繼承 LinearLayout 搭出骨架

先把 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。

第三步:onFinishInflate 中初始化子 View

@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 幾乎沒有學習成本,卻能解決大多數「重複卡片」問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved