[英]Android Custom Layout - onDraw() never gets called
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TableView tv = new TableView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
setContentView(tv);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
public class TableView extends ViewGroup {
private Paint oval;
private RectF rect;
public TableView(Context context) {
super(context);
oval= new Paint(Paint.ANTI_ALIAS_FLAG);
oval.setColor(Color.GREEN);
}
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawOval(rect , oval);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int wspec = MeasureSpec.makeMeasureSpec(
getMeasuredWidth(), MeasureSpec.EXACTLY);
int hspec = MeasureSpec.makeMeasureSpec(
getMeasuredHeight(), MeasureSpec.EXACTLY);
for(int i=0; i<getChildCount(); i++){
View v = getChildAt(i);
v.measure(wspec, hspec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
float w=r-l;
float h=b-t;
rect=new RectF(w/8,h/8,7*w/8,7*h/8);
float theta = (float) (2 * Math.PI / getChildCount());
for(int i=0; i< getChildCount(); i++) {
View v = getChildAt(i);
w = (rect.right-rect.left)/2;
h = (rect.bottom-rect.top)/2;
float half = Math.max(w, h)/2;
float centerX = rect.centerX()+w*FloatMath.cos(theta);
float centerY = rect.centerY()+h*FloatMath.sin(theta);
v.layout((int)(centerX-half),(int)(centerY-half),(int)(centerX+half),(int)(centerY+half));
}
}
}
那么几乎没有好的和深入的教程,几乎没有关于如何正确进行自定义布局的任何数据,所以我试图弄清楚它是如何完成的,我想要实现的是在中心绘制绿色椭圆的布局屏幕,我希望这个布局的每个孩子都围绕椭圆形布局。
你可以把那个椭圆形想象成一张扑克桌,我希望这种布局的孩子能够坐在它周围。
这段代码目前发生的是我得到一个没有椭圆的白色应用程序scren,所以我调试它,看到onDraw永远不会被调用...
3个问题:
如果我弄错了,你们可以指导我正确的方向,或者有任何与这个主题相关的示例或教程的链接也会有所帮助!
默认情况下,不为ViewGroup
对象调用onDraw()
。 相反,您可以覆盖dispatchDraw()
。
或者,您可以通过在TableView
构造函数中调用setWillNotDraw(false)
来启用ViewGroup
绘图。
编辑:
对于#2: - 在构造函数中初始化它,然后在onLayout()
方法中调用rect.set()
。
对于#3: - 是的,据我所知,超级调用会处理它,你不应该处理它,除非你需要自定义子项的绘制方式。
如果你想要画布重新调用invalidate(),那么onDraw()方法将被重新执行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.