我嘗試在XML中使用我自己的SurfaceView,並且我無法做到這一點。我得到NullPointerException。 根據互聯網就應該是這樣的:
活動:如何將自定義SurfaceView添加到XML佈局
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異常。
SurfaceView:
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>
我在創建曲面時調用它。它工作正常。 – zie1ony 2012-08-13 06:26:54