尝试运行我的应用时出现以下错误:
570466
我的自定义类绘制画布:
java.lang.RuntimeException: Unable to start activity ComponentInfo{g.companieshouse.companieshouse/g.companieshouse.companieshouse.GraphActivity}: android.view.InflateException: Binary XML file line #9: Binary XML file line #9: Error inflating class g.companieshouse.companieshouse.DrawGraphTest
活动:
public class DrawGraphTest extends View {
int mWidth = this.getResources().getDisplayMetrics().widthPixels;
int mHeight = this.getResources().getDisplayMetrics().heightPixels;
public DrawGraphTest(Context context) {
super(context);
//Various paints and such...
//Set point to middle of screen
point1 = new Point(mWidth / 2, mHeight / 2);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//Draw various stuff to canvas
}
XML:
public class GraphActivity extends AppCompatActivity {
DrawGraphTest drawGraphTest;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_graph);
drawGraphTest = (DrawGraphTest)findViewById(R.id.drawGraphTest);
}
}
我还想问一下是否可以缩放“ DrawGraphTest”类中绘制的内容,以使其适合活动中自定义视图的范围?
目前,它已设置为适合正在运行该应用程序的任何设备的整个屏幕(请参见point1),干杯!
答案 0 :(得分:1)
您缺少用于通过XML扩展布局的构造函数之一:
public class DrawGraphTest extends View {
int mWidth = this.getResources().getDisplayMetrics().widthPixels;
int mHeight = this.getResources().getDisplayMetrics().heightPixels;
// This constructor is used only if you instantiate your view dinamically (java)
public DrawGraphTest(Context context) {
super(context);
init();
}
// You are missing this constructor.. Add it so Android can instantiate your view via xml
public DrawGraphTest(final Context context, final AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
//Various paints and such...
//Set point to middle of screen
point1 = new Point(mWidth / 2, mHeight / 2);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//Draw various stuff to canvas
}
}