0

我正在尝试将自定义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("constructor", "done"); 在 SineWaveSurfaceView 的构造函数中甚至没有出现。

我做错了什么,因为当我做类似的事情时

sineWaveSurfaceView = new sineWaveSurfaceView(this);

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

4

1 回答 1

4

正如评论中解释的veryBadalloc,似乎从xml 膨胀启动了第二个构造函数,因此我的代码毕竟可以工作。

于 2013-06-04T11:22:42.207 回答