【问题标题】:CustomView in android throws inflate exceptionandroid中的CustomView抛出inflate异常
【发布时间】:2015-08-30 08:52:09
【问题描述】:

我必须在我的 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)

是什么原因?我的代码有什么问题吗?我该如何解决这个问题?

【问题讨论】:

    标签: android android-layout android-custom-view inflate-exception


    【解决方案1】:

    尝试改变:

    public class CustomView extends TextView {
    
        Paint customPaint;
    
        public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        customPaint = new Paint();
    }
    

    类构造函数名称不一样。

    View 类没有方法android:text="" 将基类更改为TextView

    【讨论】:

    • 扩展 View 和 TextView 有什么区别?如果它与 TextView 一起使用,它也应该与 View 一起使用。所以逻辑上这是不正确的
    • View 类没有方法android:text="" 将基类更改为TextView
    • 删除了,但还是一样
    • CustomView 没有使用 23-arguments View 构造函数...查看我的编辑..
    • 在传递属性集对象后它可以工作。如何从为视图定义的 xml 属性中设置背景颜色?
    猜你喜欢
    • 2012-01-31
    • 1970-01-01
    • 2012-09-30
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 2014-09-16
    相关资源
    最近更新 更多