androd---自定义VIEW实现网格布局

androd---自定义VIEW实现网格布局_第1张图片

今天在说下自定义VIEW--- 实现网格布局的这个功能吧。最近这个需求是检测手机屏幕是否出现问题,所以需要触摸屏幕网格,看是否会变色,如果不会变色,说明屏幕对应这块网格有问题。希望对大家在后面的类似需求的时候,有帮助


直接上代码吧

public class GridRelativeLayout extends RelativeLayout {
	private Canvas myCanvas;
	private int horGrid = 100, verGrid = 100;//水平网格和竖直网格
	private int screenW, screenH;//屏幕宽和高
	private boolean initOver = false;//初始化标签

	public GridRelativeLayout(Context context) {
		super(context);
		setWillNotDraw(false);
	}

	public GridRelativeLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		setWillNotDraw(false);
	}

	public GridRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		setWillNotDraw(false);
		this.setOnClickListener(new OnClickListener() {


			@Override
			public void onClick(View v) {



			}
		});
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		this.myCanvas = canvas;
		Paint paint = new Paint();
		paint.setColor(Color.BLACK);//颜色
		paint.setStrokeWidth(3);//线宽
		int verNum = (int)(screenH / verGrid) + 1;
		int horNum = 9;
		if (initOver) {
			for (int i = 0; i < verNum; i++) {
				canvas.drawLine(0, i * verGrid - 1, screenW, i * verGrid - 1,
						paint);
			}
			for (int i = 0; i < horNum-1; i++) {
				canvas.drawLine((i+1)*(screenW/horNum), 1, (i+1)*(screenW/horNum), screenH,
						paint);
			}
		}
	}

	/**设置网格线参数**/
	public void setInf(int vergrid, int horgrid, int screenW, int screenH) {
		this.verGrid = vergrid;
		this.horGrid = horgrid;
		this.screenW = screenW;
		this.screenH = screenH;
		initOver = true;
		postInvalidate();
	}

其实核心需要大家去计算和考虑的问题 就是这几行代码

	for (int i = 0; i < verNum; i++) {
				canvas.drawLine(0, i * verGrid - 1, screenW, i * verGrid - 1,
						paint);
			}
			for (int i = 0; i < horNum-1; i++) {
				canvas.drawLine((i+1)*(screenW/horNum), 1, (i+1)*(screenW/horNum), screenH,
						paint);
			}

起点的X, Y 坐标,终点的X,Y坐标



你可能感兴趣的:(android自定义)