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

Android 自定義控件(六):動態控制 ImageView 高度的 RatioImageView

編輯:關於 Android 程式設計

列表裡的封面圖、視頻縮略圖,往往要求按固定寬高比展示,而容器寬度又是自適應的。這種「寬度由布局決定、高度按比例推算」的需求,用普通 ImageView 滿足不了,需要自定義一個。

思路

核心在 onMeasure()。父容器在測量子 View 時會傳入 widthMeasureSpec 和 heightMeasureSpec,其中已經帶有父容器計算好的尺寸。我們只需要從寬度的測量規則中取出 size,除以寬高比算出高度,再重新組裝一個 heightMeasureSpec 交給 super.onMeasure()。

順帶複習一下 MeasureSpec:它由 size 和 mode 兩部分組成。mode 有三種取值——AT_MOST 對應 wrap_content,EXACTLY 對應確定的 dp 值或 match_parent,UNSPECIFIED 表示未指定,常見於 ListView item 的測量。

代碼實現

public class RatioImageView extends ImageView {

    private float ratio = 0f;   // 寬高比

    public RatioImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public RatioImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        ratio = attrs.getAttributeFloatValue(
                "https://schemas.android.com/apk/res/com.example.imageview",
                "ratio", 0f);
    }

    public RatioImageView(Context context) {
        super(context);
    }

    public void setRatio(float ratio) {
        this.ratio = ratio;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        if (ratio != 0) {
            float height = width / ratio;
            heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) height, MeasureSpec.EXACTLY);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

注意 getAttributeFloatValue() 的第一個參數是命名空間地址,要和布局中聲明的一致。

添加自定義屬性

(1)在 res/values/attrs.xml 中聲明

<resources>
    <declare-styleable name="RatioImageView">
        <attr name="ratio" format="float" />
    </declare-styleable>
</resources>

(2)在布局中使用

先在根布局聲明命名空間,這裡用 example 作為前綴,指向包名路徑:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:example="https://schemas.android.com/apk/res/com.example.imageview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <com.example.imageview.ui.view.RatioImageView
        android:id="@+id/iv_image"
        android:layout_width="match_parent"
        android:layout_height="180dp"
        android:scaleType="fitXY"
        example:ratio="2.5" />
</LinearLayout>

有兩個細節容易出錯:一是自定義屬性的值不能帶 f 後綴,要寫 2.5 而不是 2.5f;二是自定義屬性的解析必須放在帶 AttributeSet 的構造方法裡,如果只在含 defStyle 的構造方法中處理,某些渲染場景下會取不到值。

如果希望更高一級的靈活性,還可以把 ratio 改成默認值可配置,並在代碼中透過 setRatio() 動態調整,配合 requestLayout() 觸發重新測量。

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