android自定义视图不膨胀

时间:2015-11-15 23:16:06

标签: android view layout-inflater

我制作了一个扩展View类的自定义视图:

 import android.content.Context;
 import android.graphics.Canvas;
 import android.view.View;

 public class DrawSurfaceView extends View
 {

private ButtonsManager BM;
public DrawSurfaceView(Context context) {
    super(context);

}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    BM.draw(canvas);
}


}

我把它包含在xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
 >

        <TextureView
        android:id="@+id/gameSurface"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

                    <com.example.trashedometer.DrawSurfaceView
                android:id="@+id/drawingSurface"
                android:layout_width="match_parent"
                android:layout_height="match_parent" 
                />

</FrameLayout>

但是在主代码设置内容视图时,它说它不能为我的自定义视图充气,为什么?

 setContentView(R.layout.activity_main);

1 个答案:

答案 0 :(得分:1)

至少还需要一个构造函数来允许XML布局中的通货膨胀。

public class DrawSurfaceView extends View {
    private ButtonsManager BM;

    public DrawSurfaceView(Context context) {
        this(context, null);
    }

    public DrawSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    ...
}