Custom Button with two TextView

前端 未结 3 1636
攒了一身酷
攒了一身酷 2020-12-11 05:34

I\'m trying to Customize button with two TextView with different typeface within a single button. For that I just extended Button and with have written the following code in

3条回答
  •  我在风中等你
    2020-12-11 06:12

    You can derive a new class from Button and override the onDraw(Canvas canvas) method. I did it for a button with an icon and a text, and it works without any xml. The main problem will be to write the text at the good place on the button. For this you can use the Paint.getTextBounds() function to get the text dimensions.

    Using a LayoutInflater is probably a better practice, but I didn't manage to make it work.

    public class CustomButton extends Button {
    
        private int     mWidth;
        private int     mHeight;
        private Bitmap  mBitmap;
        private String  mText;
    
        private Paint   mPaintIcon;
        private Rect    mRectIconSrc;
        private Rect    mRectIconDst;
        private Paint   mPaintText;
    
        public CustomButton(Context context, Bitmap bitmap, int width, int height, String text) {
            super(context);
    
            mBitmap = bitmap;
            mWidth = width;
            mHeight = height;
            mText = text;
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
            setLayoutParams(params);
    
            mPaintIcon = new Paint();
            mRectIconSrc = new Rect(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
            mRectIconDst = new Rect(0, 0, mHeight, mHeight);
    
            mPaintText = new Paint();
            mPaintText.setColor(0xFF778800);
            mPaintText.setTextSize(30);
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
    
            canvas.drawBitmap(mBitmap, mRectIconSrc, mRectIconDst, mPaintIcon);
            canvas.drawText(mText, mWidth/4, mHeight*2/3, mPaintText);
        }
    
    }
    

提交回复
热议问题