【組合控制元件】android自定義控制元件之帶文字的ImageView

王世暉發表於2016-03-15

android自帶的ImageView控制元件是不能新增文字的,如果出現大量ImageView和TextView同時出現的佈局,可以組合定義一個控制元件,將ImageView和TextView組合成一個控制元件

如下圖所示:


public class ImageButtonWithText extends LinearLayout {
    public   ImageView imageView;
    public TextView   textView;
    public ImageButtonWithText(Context context,AttributeSet attrs) {
        super(context,attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ImageButtonWithText);
        /*
        * 在attrs.xml新增屬性:
        *   <declare-styleable name="ImageButtonWithText">
             <attr name="picture" format="reference"/>
            </declare-styleable>
        * */
        int picture_id = a.getResourceId(R.styleable.ImageButtonWithText_picture,-1);
        /**
         * Recycle the TypedArray, to be re-used by a later caller. After calling
         * this function you must not ever touch the typed array again.
         */
        a.recycle();
        imageView = new ImageView(context, attrs);
        imageView.setPadding(10, 10, 10, 10);
        /**
         * Sets a drawable as the content of this ImageView.
         * This does Bitmap reading and decoding on the UI
         * thread, which can cause a latency hiccup.  If that's a concern,
         * consider using setImageDrawable(android.graphics.drawable.Drawable) or
         * setImageBitmap(android.graphics.Bitmap) instead.
         * 直接在UI執行緒讀取和解碼Bitmap,可能會存在潛在的效能問題
         * 可以考慮使用 setImageDrawable(android.graphics.drawable.Drawable)
         * 或者setImageBitmap(android.graphics.Bitmap) 代替
         */
        imageView.setImageResource(picture_id);
        textView =new TextView(context, attrs);
        /**
         * Sets the horizontal alignment of the text and the
         * vertical gravity that will be used when there is extra space
         * in the TextView beyond what is required for the text itself.
         */
        //水平居中
        textView.setGravity(android.view.Gravity.CENTER_HORIZONTAL);
        textView.setPadding(0, 0, 0, 0);
        setClickable(true);
        setFocusable(true);
        setOrientation(LinearLayout.VERTICAL);
        addView(imageView);
        addView(textView);
    }
    public void setText(int resId) {
        textView.setText(resId);
    }
    public void setText(CharSequence buttonText) {
        textView.setText(buttonText);
    }
    public void setTextColor(int color) {
        textView.setTextColor(color);
    }
佈局檔案中這麼使用:

<com.uestcneon.chuji.changjianglife.share.ImageButtonWithText
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    style="@style/hisCardTable"
    custom:picture="@mipmap/his_card_company"
    android:id="@+id/imgbtn_company"
    android:text="公司(1)" >
</com.uestcneon.chuji.changjianglife.share.ImageButtonWithText>
圖片將通過自定義的custom:picture傳遞給ImageView控制元件,文字將通過android:text傳遞給TextView

相關文章