Android自定义View - 为 View 添加边框

一、环境

  1. 安卓系统:4.2
  2. 操作系统:Win 8.1
  3. 工具:Android Studio

二、添加边框

  • 可以用背景图片的方式。
  • 自定义 View,在 onDraw 方法绘制边框
public class MyRelativeLayout extends RelativeLayout {    
        public MyRelativeLayout(Context context) {        
            super(context);    
        }    

        public MyRelativeLayout(Context context, AttributeSet attrs) {        
            super(context, attrs);    
        } 

        public MyRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {        
            super(context, attrs, defStyleAttr);    
        }    

        @Override    
        protected void onDraw(Canvas canvas) {        
            Paint paint = new Paint();
            paint.setColor(0xFF000000);     //画笔颜色        
            paint.setStrokeWidth(5);        //画笔粗细
            int width = this.getWidth();        
            int height = this.getHeight();
            //drawLine 参数为坐标(X开始,Y开始,X结束,Y结束,画笔)
            canvas.drawLine(1, height-1, width-1, height-1, paint);        
            super.onDraw(canvas);    
        }
}

你可能感兴趣的:(Android自定义View - 为 View 添加边框)