【组合控件】android自定义控件之带文字的ImageView

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

你可能感兴趣的:(【组合控件】android自定义控件之带文字的ImageView)