萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 自定義圖文 Button 實現方案對比:drawableLeft、繼承 Button 重繪、合成佈局封裝、現代 Material Button

圖文混排 Button 是高頻 UI 需求。本文對比四種實現方案:原生 drawableLeft/Top、繼承 Button 重寫 onDraw、合成佈局 (RelativeLayout/LinearLayout) 封裝、MaterialButton + iconGravity,分析優缺點、適用場景與性能差異。

方案一:原生屬性 — 最簡單、性能最優

<Button
    android:id="@+id/btn_train"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="火車"
    android:textSize="16sp"
    android:textColor="#000000"
    android:drawableLeft="@drawable/ic_train"
    android:drawablePadding="8dp"
    android:padding="12dp"
    android:background="@drawable/btn_bg_selector" />
  • 優點: 零代碼、系統原生渲染、自動處理狀態 (pressed/focused/disabled)、支援 drawableStart/End/Top/Bottom (RTL 友好)。
  • 缺點: 圖標大小不可直接控制 (需在 Drawable 內部調整)、圖文相對位置固定、無法實現圖標在文字上方且居中 (需 drawableTop 但文字基線對齊難控制)。
  • 圖標背景必須透明,否則按下態顏色不會覆蓋圖標區域。

方案二:繼承 Button 重寫 onDraw — 完全控制繪製

public class ImageTextButton extends Button {
    private Drawable icon;
    private int iconWidth, iconHeight;
    private int iconGravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;

    public ImageTextButton(Context ctx, AttributeSet attrs) {
        super(ctx, attrs);
        TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.ImageTextButton);
        icon = a.getDrawable(R.styleable.ImageTextButton_icon);
        iconWidth = a.getDimensionPixelSize(R.styleable.ImageTextButton_iconWidth, -1);
        iconHeight = a.getDimensionPixelSize(R.styleable.ImageTextButton_iconHeight, -1);
        iconGravity = a.getInt(R.styleable.ImageTextButton_iconGravity, iconGravity);
        a.recycle();
        if (icon != null) icon.setCallback(this);
    }

    @Override protected void onDraw(Canvas canvas) {
        super.onDraw(canvas); // 繪製背景與文字
        if (icon == null) return;
        // 計算圖標繪製區域 (根據 iconGravity、padding、文字寬度)
        // 此處省略詳細佈局計算邏輯...
        icon.setBounds(iconLeft, iconTop, iconLeft + iconWidth, iconTop + iconHeight);
        icon.draw(canvas);
    }

    @Override protected boolean verifyDrawable(Drawable who) {
        return who == icon || super.verifyDrawable(who);
    }
}
  • 優點:像素級控制圖標位置、大小、旋轉、動畫。
  • 缺點:需手動計算佈局、處理文字換行/省略、狀態變化手動觸發 invalidate、維護成本高。

方案三:合成佈局封裝 — 靈活組合、支援複雜結構

res/layout/widget_image_text_button.xml

<merge xmlns:android="https://schemas.android.com/apk/res/android">
    <ImageView android:id="@+id/iv_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter" />
    <TextView android:id="@+id/tv_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:ellipsize="end"
        android:maxLines="1" />
</merge>

ImageTextButton extends LinearLayout

public class ImageTextButton extends LinearLayout {
    private ImageView ivIcon;
    private TextView tvText;

    public ImageTextButton(Context ctx, AttributeSet attrs) {
        super(ctx, attrs);
        setOrientation(HORIZONTAL); // 或 VERTICAL
        setGravity(Gravity.CENTER);
        LayoutInflater.from(ctx).inflate(R.layout.widget_image_text_button, this, true);
        ivIcon = findViewById(R.id.iv_icon);
        tvText = findViewById(R.id.tv_text);
        // 解析自定義屬性設置圖標、文字、間距...
    }
    // 提供 setText, setIcon, setIconPosition 等公共方法
}
  • 優點:佈局與邏輯分離、支援垂直/水平/疊加任意排版、可嵌套進階動畫 (圖標旋轉、文字漸變)。
  • 缺點:增加 View 層級、需手動轉發點擊/長按/觸摸事件、無法直接使用 Button 原生狀態列表動畫。

方案四:MaterialButton (API 21+ / Material Components) — 現代標準

<com.google.android.material.button.MaterialButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="下載"
    app:icon="@drawable/ic_download"
    app:iconGravity="textStart"        // textStart | textEnd | textTop | textBottom
    app:iconSize="20dp"
    app:iconPadding="8dp"
    app:cornerRadius="8dp"
    style="@style/Widget.MaterialComponents.Button.OutlinedButton" />
  • 優點:Material Design 規範、內建 Ripple、狀態層、圖標著色、圖標位置四向可配、佈局預覽即時生效。
  • 缺點:需引入 material 庫、最低 API 21 (含兼容庫)。

五、方案選型建議

現代 Android 開發首選 MaterialButton,舊專案漸進式遷移;特殊定製場景再考慮方案二/三。

copyright © 萬盛學電腦網 all rights reserved
場景推薦方案理由
簡單圖文按鈕、列表項操作方案一 (drawableLeft)零代碼、性能最好、系統原生狀態
需精確控制圖標大小/位置/動畫方案二 (繼承 Button)繪製完全可控
複雜結構 (圖標+主標題+副標題、徽章、進度環)方案三 (合成佈局)靈活組合子 View
新專案 / Material Design 風格方案四 (MaterialButton)規範統一、功能豐富、維護成本低