我必须使用画布类在其上添加框架和多个图像。但我的问题是我必须在我的活动类中使用画布视图。我想将此画布视图用作小部件,以便可以在我的 XML 中使用它。
我通过使用以下代码进行了尝试:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.View;
public class TwoDee extends View {
private int mWidth;
private int mHeight;
public TwoDee(Context context) {
super(context);
}
public TwoDee(Context context, AttributeSet attribs) {
super(context, attribs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.GRAY);
paint.setStyle(Style.FILL);
canvas.drawPaint(paint);
paint.setColor(Color.BLUE);
canvas.drawLine(0, 0, mWidth, mHeight, paint);
canvas.drawLine(mWidth, 0, 0, mHeight, paint);
paint.setColor(Color.RED);
canvas.drawText("0 kal", 50, 85, paint);
canvas.save();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
mWidth = View.MeasureSpec.getSize(widthMeasureSpec);
mHeight = View.MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(mWidth, mHeight);
}
public void setImage(Drawable myImg) {
newImg = myImg;
invalidate();
}
}
并像这样在我的 xml 类中使用它:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<com.yourapphere.TwoDee
android:id="@+id/twoDee1"
android:layout_width="150dp"
android:layout_height="100dp"
/>
</LinearLayout>
我正在我的活动类中访问它,如下所示:
TwoDee myCanvas;
myCanvas = (TwoDee)findViewById(R.id.twoDee1);
myCanvas.setImage(drawable);
我的问题是,当我尝试从我的活动类中调用 setImage() 函数时,它显示空指针异常。我应该怎么做才能使用我的 Activity 类在画布视图中添加图像。我不想使用setContentView
,因为这只会使 Canvas View 显示在我的活动中。
日志输出:
FATAL EXCEPTION: main
java.lang.NullPointerException
at iTagz.android.Dialog_ImagePreview$1.onClick(Dialog_ImagePreview.java:84)
at android.view.View.performClick(View.java:2485)
at android.view.View$PerformClick.run(View.java:9081)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3770)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:638)
at dalvik.system.NativeStart.main(Native Method)
Dialog_ImagePreview是我调用SetImage方法的活动。