定义自己的布局RelativeLayout 绘制网格线
在Android画线必须由一个载体,无论是控制,无论是布局。实际上它们是从继承View。由画线的方式自己的控制或布局的定义是最常见的。
以下是在其定义中的小样本实现RelativeLayout绘制网络格线
代码下载:http://download.csdn.net/detail/yxg190221/7589287
自己定义控件代码:
</pre><pre name="code" class="java">package layout.layout.ex; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.widget.RelativeLayout; 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); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); this.myCanvas = canvas; Paint paint = new Paint(); paint.setColor(android.graphics.Color.YELLOW);//颜色 paint.setStrokeWidth(3);//线宽 int verNum = (int)(screenH / verGrid) + 1; int horNum = (int)(screenW / horGrid) + 1; 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; i++) { canvas.drawLine(i * horGrid - 1, 0, i * horGrid - 1, 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(); } /**擦除网格线**/ public void clearLine() { initOver = false; postInvalidate(); } }主程序代码:
package com.example.test005; import layout.layout.ex.GridRelativeLayout; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { private GridRelativeLayout rl; private Button btnDraw,btnClear; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rl=(GridRelativeLayout)findViewById(R.id.rl); btnDraw=(Button)findViewById(R.id.button1); btnClear=(Button)findViewById(R.id.button2); btnDraw.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { rl.setInf(100, 100, 1280, 720);//画网格线 } }); btnClear.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { rl.clearLine();//擦除网格线 } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } }
版权声明:本文博客原创文章,博客,未经同意,不得转载。