I have to create a custom view in my android application, for that I have wrote code as follows
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);
}
}
Activity
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);
}
}
but while I am running the application I am getting error ::
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)
What is the reason ? is there any problem in my code ? how do I resolve this ?
Try to change:
public class CustomView extends TextView {
Paint customPaint;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
customPaint = new Paint();
}
Name of the class constructor are not the same.
View
class does not have method android:text=""
change base class to TextView