我尝试创建一个绘图应用程序。在我的主要活动中,我有一个包含图纸视图的XML文件
<app.color.DrawingView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="@+id/drawing"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#FFFFFFFF"
android:layout_above="@+id/settings"
android:layout_alignParentTop="true" />
这是基于我的绘图视图类:
package app.color;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class DrawingView extends View {
private Paint paint = new Paint();
private Path path = new Path();
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(5f);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Get the coordinates of the touch event.
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Set a new starting point
path.moveTo(eventX, return true;
case MotionEvent.ACTION_MOVE:
// Connect the points
path.lineTo(eventX, eventY);
break;
default:
return false;
}
// Makes our view repaint and call onDraw
invalidate();
return true;
}
public void setColor(String newColor){
invalidate();
int paintColor = Color.parseColor(newColor);
paint.setColor(paintColor);
}
}
然后在按钮单击的另一个活动中我有一个方法,我希望能够在drawingView中调用setColor方法来更改颜色。但是它不会让我这样做,因为无法从静态上下文中引用&#34;非静态方法&#34;
public void toBlack(View view)
{
DrawingView.setColor("#00000");
Intent intent = new Intent(Colors.this, MainActivity.class);
startActivity(intent);
}
答案 0 :(得分:1)
创建DrawingView的实例。
那就像,
DrawingView drawingview = new DrawingView();
drawingview.setColor("#00000");
setColor
是一个实例方法,这意味着您需要一个DrawingView
类的实例才能调用它。您尝试在DrawingView
类型本身上调用它。
只需将您的代码设为
即可DrawingView dv = new DrawingView();
dv.setColor("#00000");
Intent intent = new Intent(Colors.this, MainActivity.class);
startActivity(intent);
例如你已经有了
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(5f);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
你也可以有另一个空的构造函数 像
public DrawingView() { }
答案 1 :(得分:0)
setColor不是静态方法。您需要在DrawingView的实例上调用它。