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

自定義 RadioButton:讓文字四邊的圖片尺寸可以隨意設定

編輯:關於 Android 程式設計

好久沒更新,寫這篇技術文的時候感覺很多東西都生疏了。於是心有感慨:我們做技術的,長時間不搞技術,那就是被技術搞。所以攻守之間,大家謹慎思量。

冬天已過,放假出去走動時,看到兩旁嫩嫩的樹葉,想起賀知章的《詠柳》:

碧玉妝成一樹高,
萬條垂下綠絲絛。
不知細葉誰裁出,
二月春風似剪刀。

猶自感歎,春天來了,美腿還會遠麼。

閒言少敘,言歸正傳。

需求與問題

前兩天朋友提出一個需求:用 RadioButton 實作應用頁面的切換。

想法很好,但出現了兩個問題:其一,界面擴展性很差;其二,RadioButton 設定圖片後,無法在 XML 中設定圖片大小,導致版面不美觀。那麼問題來了——如何設定這個圖片的大小?

網路上常見的答案

常見回答是:在程式碼中動態設定圖片大小,然後設定到版面配置上。

mRadioButton.setCompoundDrawables(left, top, right, bottom);

參數型別都是 Drawable,分別代表左、上、右、下四個方向要顯示的圖片。

查閱 setCompoundDrawables(left, top, right, bottom) 的說明,有這麼一段:

Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text. Use null if you do not want a Drawable there. The Drawables must already have had Drawable.setBounds called.

也就是說,呼叫這個方法之前,必須先用 Drawable.setBounds() 為圖片設定邊界,也就是要顯示的大小。

另一個等效方法

setCompoundDrawablesWithIntrinsicBounds(drawableLeft, drawableTop, drawableRight, drawableBottom);

進入源碼看看它的實作:

public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top,
        Drawable right, Drawable bottom) {
    if (left != null) {
        left.setBounds(0, 0, left.getIntrinsicWidth(), left.getIntrinsicHeight());
    }
    if (right != null) {
        right.setBounds(0, 0, right.getIntrinsicWidth(), right.getIntrinsicHeight());
    }
    if (top != null) {
        top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight());
    }
    if (bottom != null) {
        bottom.setBounds(0, 0, bottom.getIntrinsicWidth(), bottom.getIntrinsicHeight());
    }
    setCompoundDrawables(left, top, right, bottom);
}

原來這個方法同樣呼叫了 setCompoundDrawables(),只是在呼叫之前,先依照圖片自身的內在尺寸設定了邊界範圍。它的註釋也寫得很清楚:

Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text. Use null if you do not want a Drawable there. The Drawables' bounds will be set to their intrinsic bounds.

意思是說:設定 drawable 顯示在文字的上下左右,不想設定的方向傳 null;圖片的邊界就是它自身固有的邊界範圍。

OK,一切明了。那麼我們只要自己改寫這個邊界值,就能達到改變圖片大小的目的。答案是肯定的。

步驟一:定義自定義屬性

先在 XML 裡準備好設定圖片大小的屬性,這裡取名為 drawableSize,另外分別給出四個方向的圖片屬性。attrs.xml 內容如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyRadioButton">
        <attr name="drawableSize" format="dimension" />
        <attr name="drawableTop" format="reference" />
        <attr name="drawableBottom" format="reference" />
        <attr name="drawableRight" format="reference" />
        <attr name="drawableLeft" format="reference" />
    </declare-styleable>
</resources>

步驟二:在程式碼中取出屬性

Drawable drawableLeft = null, drawableTop = null, drawableRight = null, drawableBottom = null;

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyRadioButton);
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
    int attr = a.getIndex(i);
    Log.i("MyRadioButton", "attr:" + attr);
    switch (attr) {
        case R.styleable.MyRadioButton_drawableSize:
            mDrawableSize = a.getDimensionPixelSize(R.styleable.MyRadioButton_drawableSize, 50);
            Log.i("MyRadioButton", "mDrawableSize:" + mDrawableSize);
            break;
        case R.styleable.MyRadioButton_drawableTop:
            drawableTop = a.getDrawable(attr);
            break;
        case R.styleable.MyRadioButton_drawableBottom:
            drawableBottom = a.getDrawable(attr);
            break;
        case R.styleable.MyRadioButton_drawableRight:
            drawableRight = a.getDrawable(attr);
            break;
        case R.styleable.MyRadioButton_drawableLeft:
            drawableLeft = a.getDrawable(attr);
            break;
        default:
            break;
    }
}
a.recycle();

這裡已經拿到了設定的圖片,以及希望顯示的大小 drawableSize。

步驟三:重寫 setCompoundDrawablesWithIntrinsicBounds

public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top,
        Drawable right, Drawable bottom) {
    if (left != null) {
        left.setBounds(0, 0, mDrawableSize, mDrawableSize);
    }
    if (right != null) {
        right.setBounds(0, 0, mDrawableSize, mDrawableSize);
    }
    if (top != null) {
        top.setBounds(0, 0, mDrawableSize, mDrawableSize);
    }
    if (bottom != null) {
        bottom.setBounds(0, 0, mDrawableSize, mDrawableSize);
    }
    setCompoundDrawables(left, top, right, bottom);
}

把邊界改成我們要的大小之後,別忘了呼叫 setCompoundDrawables(),這樣圖片才會真正顯示到畫面上。

步驟四:版面配置

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:myradio="https://schemas.android.com/apk/res/com.example.test"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">

        <FrameLayout
            android:id="@+id/tab_content"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1.0"
            android:background="#FFFFFF" />

        <RadioGroup
            android:id="@+id/rgs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/whiet"
            android:gravity="center"
            android:orientation="horizontal">

            <com.example.test.MyRadioButton
                android:id="@+id/tab_a"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:background="@color/whiet"
                android:button="@null"
                android:clickable="true"
                android:gravity="center"
                android:text="首頁"
                android:textSize="13sp"
                myradio:drawableSize="20dp"
                myradio:drawableTop="@drawable/shouye_radiobutton" />

            <com.example.test.MyRadioButton
                android:id="@+id/tab_b"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:background="@color/whiet"
                android:button="@null"
                android:checked="true"
                android:clickable="true"
                android:gravity="center"
                android:text="分類"
                android:textSize="13sp"
                myradio:drawableSize="30dp"
                myradio:drawableTop="@drawable/fenlei_radiobutton" />

            <RadioButton
                android:id="@+id/tab_c"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="@color/whiet"
                android:button="@null"
                android:drawableTop="@drawable/gouwuche_bg"
                android:gravity="center"
                android:text="購物車"
                android:textSize="13sp" />

            <RadioButton
                android:id="@+id/tab_d"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:background="@color/whiet"
                android:button="@null"
                android:drawableTop="@drawable/faxian_radiobutton"
                android:gravity="center"
                android:text="發現"
                android:textSize="13sp" />

            <RadioButton
                android:id="@+id/tab_e"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:background="@color/whiet"
                android:button="@null"
                android:drawableTop="@drawable/wode_radiobutton"
                android:gravity="center"
                android:text="我的"
                android:textSize="13sp" />
        </RadioGroup>
    </LinearLayout>
</RelativeLayout>

其中頭兩個 RadioButton 用了自定義的版本,另外三個是系統原生的,用來做對比。使用自定義屬性時別忘了宣告命名空間,自定義的 RadioButton 也要記得加上 android:clickable="true"。

完整源碼

package com.example.test;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.RadioButton;

public class MyRadioButton extends RadioButton {

    private int mDrawableSize;   // XML 中設定的大小

    public MyRadioButton(Context context) {
        this(context, null, 0);
    }

    public MyRadioButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

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

        Drawable drawableLeft = null, drawableTop = null,
                drawableRight = null, drawableBottom = null;

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyRadioButton);
        int n = a.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            Log.i("MyRadioButton", "attr:" + attr);
            switch (attr) {
                case R.styleable.MyRadioButton_drawableSize:
                    mDrawableSize = a.getDimensionPixelSize(
                            R.styleable.MyRadioButton_drawableSize, 50);
                    break;
                case R.styleable.MyRadioButton_drawableTop:
                    drawableTop = a.getDrawable(attr);
                    break;
                case R.styleable.MyRadioButton_drawableBottom:
                    drawableBottom = a.getDrawable(attr);
                    break;
                case R.styleable.MyRadioButton_drawableRight:
                    drawableRight = a.getDrawable(attr);
                    break;
                case R.styleable.MyRadioButton_drawableLeft:
                    drawableLeft = a.getDrawable(attr);
                    break;
                default:
                    break;
            }
        }
        a.recycle();

        setCompoundDrawablesWithIntrinsicBounds(drawableLeft, drawableTop,
                drawableRight, drawableBottom);
    }

    @Override
    public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top,
            Drawable right, Drawable bottom) {
        if (left != null) {
            left.setBounds(0, 0, mDrawableSize, mDrawableSize);
        }
        if (right != null) {
            right.setBounds(0, 0, mDrawableSize, mDrawableSize);
        }
        if (top != null) {
            top.setBounds(0, 0, mDrawableSize, mDrawableSize);
        }
        if (bottom != null) {
            bottom.setBounds(0, 0, mDrawableSize, mDrawableSize);
        }
        setCompoundDrawables(left, top, right, bottom);
    }
}

程式碼很簡單,註釋都在文中說明了。

至此,能自定義改變 Drawable 圖片大小的 RadioButton 就完成了。經此一役可以發現,只要願意往下讀一層源碼,客製化的空間比想像中大得多——沒有做不到,只有想不到。

轉載請注明出處。

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