将surfaceView与xml一起使用

时间:2012-06-12 16:27:47

标签: android surfaceview

我引用Using MySurfaceView with main.xml (android),代码为“textView1.setText(”set“);”在onCreate方法里面会有一个错误(tv1 =(TextView)findViewById(R.id.tv1); - 声明工作正常)。我该如何解决这个问题?提前感谢您的帮助。

public class For12junonly2Activity extends Activity {


TextView tv1;
EditText et1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    try
    {
    tv1 = (TextView)findViewById(R.id.tv1);     
    tv1.setText("Hi");
    }catch(Exception e)
    {
        Log.d("prob",String.valueOf(e));
    }
    et1 = (EditText)findViewById(R.id.et1); 
    setContentView(R.layout.main);

    float sss = surf.getX();
    Log.d("float create",String.valueOf(sss));
}

}

 class surf extends SurfaceView implements SurfaceHolder.Callback
{
...... from https://stackoverflow.com/q/8149225/1393006




public boolean onTouchEvent(MotionEvent event)
{   
    canvas.drawBitmap(myBitmap, event.getX() - (myBitmap.getWidth() / 2), event.getY() - (myBitmap.getHeight() / 2), null);
    canvas.drawCircle(event.getX(), event.getY(), 10, paint);
    surfaceHolder.unlockCanvasAndPost(canvas);
    Log.d("onTouch","X: "+event.getX()+" , Y: "+event.getY());
    x = event.getX();
    return true;
}
}
来自xml的

代码

<TextView
    android:id="@+id/tv1" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="tv1" />

<te.de11.surf
    android:id="@+id/surfaceview" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
   />
来自log cat的

错误消息

D/dalvikvm(443): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(443): NOTE: attach of thread 'Binder Thread #3' failed
D/prob(363): java.lang.NullPointerException
D/float create(363): 0.0
I/ActivityManager(60): Displayed te.de11/.For12junonly2Activity: +1s29ms
D/dalvikvm(127): GC_EXPLICIT freed 66K, 52% free 2855K/5895K, external 4998K/6087K, paused 44ms

1 个答案:

答案 0 :(得分:0)

在将XML设置为活动视图之前,您正尝试在XML中引用TextView。由于您的Activity现在没有任何视图,任何findViewById()调用都将导致NullPointerException。要修复它,只需在引用XML中使用的任何小部件之前调用setContentView()。它通常在super()调用后直接调用。