我必须在我的android应用程序中创建一个自定义视图,因为我编写了如下代码
XML
<com.package.custom.CustomView
android:id="@+id/my_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
CustomView.java
package com.package.custom;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
public class CustomView extends View {
Paint customPaint;
public CustomView(Context context) {
super(context);
customPaint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = this.getMeasuredWidth();
int height = this.getMeasuredHeight();
customPaint.setStyle(Paint.Style.FILL);
customPaint.setAntiAlias(true);
customPaint.setColor(getResources().getColor(android.R.color.holo_blue_dark));
canvas.drawPaint(customPaint);
}
}
活动
public class CustomViewActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_button);
CustomView customView = (CustomView) findViewById(R.id.my_view);
}
}
但是当我运行应用程序时,我收到错误::
3178-3178/com.package.custom E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.package.custom/com.package.custom.CustomViewActivity}: android.view.InflateException: Binary XML file line #11: Error inflating class com.package.custom.CustomView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2255)
是什么原因?我的代码有什么问题吗?我该如何解决这个问题?
答案 0 :(得分:0)
尝试改变:
public class CustomView extends TextView {
Paint customPaint;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
customPaint = new Paint();
}
类构造函数的名称不相同。
View
类没有方法android:text=""
将基类更改为TextView