我有一个扩展视图的类。下面是构造函数。在构造函数中,我将值赋给private int r,g,b;
。分配正确的值。
public CanvasView(Context c, int r, int g, int b) {
super(c);
context = c;
this.r = r;
this.g = g;
this.b = b;
Log.i("RGB:", "r" + r + "g" + g + "b" + b); //logs correct values
}
在onDraw(见下文)中,当我访问所有值时,它们都为零。
@Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
hsv = new float[3];
Color.RGBToHSV(r, g, b, hsv);
hsv[2] = getVal();
Log.i("RGBdraw:", "r" + r + "g" + g + "b" + b); //values are all 0
if (canvas != null){
canvas.drawColor(Color.rgb(r, g, b));
}
}
我认为在分配私有变量时,它们可以访问整个类吗? 非常感谢任何帮助。
修改 这是最小的例子
在另一个课程中,我创建了视图CanvasView mCanvasView = new CanvasView(mContext, 255, 0, 171);
以下是名为CanvasView的类,它由上面的代码创建。我将3个整数传递给CanvasView。
public class CanvasView extends View {
private Context context;
private int r,g,b;
public CanvasView(Context c, int r, int g, int b) {
super(c);
context = c;
this.r = r;
this.g = g;
this.b = b;
Log.i("RGB:", "r" + r + "g" + g + "b" + b); //Correct values are logged
}
@Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
Log.i("RGB draw:", "r" + r + "g"+g + "b"+b); //Values here are all 0
if (canvas != null){
canvas.drawColor(Color.rgb(r, g, b));
}
}
}
答案 0 :(得分:2)
而不是像在java中那样创建类:CanvasView mCanvasView = new CanvasView(mContext, 255, 0, 171);
以android方式创建类:CanvasView mView = (CanvasView) findViewById(R.id.canvasView);
然后使用红绿蓝的getter和setter
public void red(int r){
this.r = r;
}
public int getRed(){
return r;
}
传递如下值:mView.red(255);