androd---自定義VIEW實現網格佈局
阿新 • • 發佈:2019-02-09
今天在說下自定義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座標