我尝试在 XML 中使用我自己的 SurfaceView,但我无法做到。我得到 NullPointerException。根据互联网,它应该如下所示:
活动:
package editor;
import android.app.Activity;
import android.os.Bundle;
import com.example.balls_menu_v1.R;
public class EditorActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editor);
EditorView ev = (EditorView) findViewById(R.id.editorView);
}
}
如果我发表评论findViewById
,我会得到 NullPointerException。
表面视图:
package editor;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class EditorView extends SurfaceView {
public EditorView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onFinishInflate() {
super.onFinishInflate();
SurfaceHolder holder = getHolder();
Canvas canvas = holder.lockCanvas();
canvas.drawColor(Color.GREEN);
holder.unlockCanvasAndPost(canvas);
}
}
布局:editor.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<editor.EditorView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/editorView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>