android button with double border and gradient

前端 未结 3 1606
南方客
南方客 2021-02-15 17:10

I want to create a custom button. This button should have a gradient and a two pixel border, but the inner and outer edge should be in a different color (example: inner is red a

3条回答
  •  执念已碎
    2021-02-15 17:40

    If you want to go by plain Java code then you need to create a class which extends the button, write all your logic in

    public void onDraw(Canvas iCanvas).

    I have pasted small code snippet from one of my project. Give it a try. thought I have not created the gradient, I have used plain colors.

    public class MyButton extends Button {
    
        private Paint m_paint1 = new Paint();
        private Paint m_paint2 = new Paint();
        private int m_color1 = 0XFF92C84D; // LIKE AN OLIVE GREEN..
        private int m_color2 = 0XFFFF0000; // LIKE AN OLIVE GREEN..
    
        private RectF innerRect1, innerRect2;
    
        public MyButton(Context context) {
            super(context);
            setBackgroundColor(Color.BLACK);
    
        }
    
        public void onDraw(Canvas iCanvas) {
            // draw the button background
            m_paint1.setColor(m_color1);
            m_paint2.setColor(m_color2);
            innerRect1 = new RectF(5, 5, getWidth() - 5, getHeight() - 5);
            innerRect2 = new RectF(10, 10, getWidth() - 10, getHeight() - 10);
            iCanvas.drawRoundRect(innerRect1, 0, 0, m_paint1);
            iCanvas.drawRoundRect(innerRect2, 0, 0, m_paint2);
        }
    
        public static RelativeLayout.LayoutParams GetRelativeParam(int iLeft,
                int iTop, int iWidth, int iHeight) {
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    iHeight, iWidth);
            params.leftMargin = iLeft;
            params.topMargin = iTop;
            return params;
        }
    }
    

    and

    RelativeLayout relLay = new RelativeLayout(this);
    
            MyButton m_button = new MyButton(this);
            setContentView(relLay);
    
            relLay.addView(m_button, MyButton.GetRelativeParam(0, 0, 100, 500));
    

提交回复
热议问题