Android - 将自定义surfaceView添加到xml定义的surfaceView无法正常工作

时间:2013-06-04 10:10:12

标签: android xml drawing surfaceview xml-layout

我正在尝试将自定义surfaceView类添加到已在xml布局中声明的surfaceView。问题是我无法获得自定义类添加xml定义的surfaceView。一些如何不开始。

这是我的代码:
MainActivity

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    sineWaveSurfaceView = (SineWaveSurfaceView) findViewById(R.id.surfaceView);
}

MainActivity布局

<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

    <mark.dijkema.android.eindopdracht.SineWaveSurfaceView
        android:id="@+id/surfaceView"
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:layout_marginTop="20dp" />

    <ListView
        android:id="@+id/song_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp" >
    </ListView>

</RelativeLayout>

SineWaveSurfaceView类

public class SineWaveSurfaceView extends SurfaceView implements SurfaceHolder.Callback
{
private Context context;

public SineWaveSurfaceView(Context context)
{
    super(context);
    // TODO Auto-generated constructor stub

    this.context = context;
    getHolder().addCallback(this);

    Log.e("constructor", "done");
}

public SineWaveSurfaceView(Context context, AttributeSet attrs)
{
    super(context, attrs);
    // TODO Auto-generated constructor stub
}

public SineWaveSurfaceView(Context context, AttributeSet attrs, int defStyle)
{
    super(context, attrs, defStyle);
    // TODO Auto-generated constructor stub
}

protected void OnDraw(Canvas canvas, int value)
{
    //canvas.drawColor(Color.WHITE);

    Paint paint = new Paint();
    paint.setColor(Color.WHITE);

    float y = Float.valueOf(String.valueOf(value)); 

    for(float x = 0; x < 200; x += 0.1f)
    {
        canvas.drawPoint(x, y, paint);
    }
}

@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3)
{
    // TODO Auto-generated method stub

}

@Override
public void surfaceCreated(SurfaceHolder arg0)
{
    // TODO Auto-generated method stub

    Log.e("start", "started");
}

@Override
public void surfaceDestroyed(SurfaceHolder arg0)
{
    // TODO Auto-generated method stub

}

}

问题是Log.e(“构造函数”,“完成”);在SineWaveSurfaceView的构造函数中甚至没有出现。

我做错了什么,因为当我做

之类的事情时
sineWaveSurfaceView = new sineWaveSurfaceView(this);

然后它可以工作,但它没有附加到xml布局中定义的surfaceView。

1 个答案:

答案 0 :(得分:4)

正如VeryBadalloc在评论中解释的那样,似乎从xml中膨胀启动了第二个构造函数,因此我的代码完全正常工作。