我有一个来自Activity类的对象:
CustomPaint customCanvasPaint=(CustomPaint) dialog.findViewById(R.id.customCanvasPaint);
如何将此对象传递给类:
public class CustomPaint extends CanvasView {
public CustomPaint(Context context) {
super(context);
initialize(context);
}
public CustomPaint(Context context, AttributeSet attrs) {
super(context, attrs);
initialize(context);
}
public void initialize(Context context){
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.custom_paint,null);
CanvasView canvasView = (CanvasView) view.findViewById(R.id.customCanvasView);
canvasView.setPaintStrokeColor(Color.RED);
canvasView.setPaintStrokeWidth(12f);
}
}
我想在初始化方法中自定义对象,但是绘制颜色和绘制宽度不会改变。 我该怎么办? 谢谢。
答案 0 :(得分:0)
public class CustomPaint extends CanvasView {
CanvasView mCanvasView;
public CustomPaint(Context context,CanvasView canvasView) {
super(context);
this.mCanvasView = canvasView;
initialize(context);
}
public CustomPaint(Context context, AttributeSet attrs,CanvasView canvasView) {
super(context, attrs);
this.mCanvasView = canvasView;
initialize(context);
}
public void initialize(Context context){
canvasView.setPaintStrokeColor(Color.RED);
canvasView.setPaintStrokeWidth(12f);
}
}
表单活动
CanvasView canvasPaint=(CanvasView) dialog.findViewById(R.id.canvasPaint);
CustomPaint mCustomPaint = new CustomPaint(this,canvasPaint);
答案 1 :(得分:0)
您可以在子类中进行必要的更改,并将此子类添加到.xml布局文件中。
CustomPaint canvasPaint=(CustomPaint) dialog.findViewById(R.id.customPaint);
为了对此视图进行更改,您应该在传递画布上将onDraw()
绘制方法覆盖到onDraw()方法。看一下这个https://developer.android.com/training/custom-views/custom-drawing.html。
答案 2 :(得分:0)
您可以通过在类中创建setter方法来传递对象:
这是你的活动:
@Override
protected void onCreate(Bundle bundle) {
//
CustomPaint view = (CustomPaint) findViewById(R.id.customPaint);
MyObject object = new MyObject("This is a test object");
view.setData(object);
view.postInvalidate();
}
从您的自定义类:
public CustomPaint extends View {
private MyObject mData;
//... Constructor and others ...
public void setData(MyObject data) {
mData = data;
}
}