1

我想创建一个自定义视图类。但是运行应用程序时出现错误。

这是我的课:

package test.start;

import android.util.AttributeSet;
import android.view.*;
import android.graphics.*;
import android.content.Context;

public class control extends View{
    private Paint paint;

    public control(Context context, AttributeSet attrs, int defStyle){
        super(context, attrs, defStyle);
        init();
    }

    public void init(){
        paint = new Paint();
        paint.setTextSize(12);
        paint.setColor(0xFF668800);
        paint.setStyle(Paint.Style.FILL);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawText("TEEEST", 100, 100, paint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        this.setMeasuredDimension(150,200);     
    }
}

和 main.XML

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 
        android:layout_width="fill_parent" 
        xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_height="fill_parent" android:orientation="vertical">
        <TextView android:id="@+id/textView1" android:text="@string/text" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
        <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/tableLayout1">
            <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:background="@drawable/custom_button" android:layout_weight="1"></Button>
            <Button android:layout_width="wrap_content"  android:id="@+id/button1" android:layout_height="40dip" android:text="@string/button" android:layout_weight="1"></Button>
            <test.control 
              android:id="@+id/control" 
              android:layout_width="match_parent" 
              android:layout_height="match_parent"> </test.control>
        </TableLayout>
    </LinearLayout>

错误信息:

无法启动活动 ComponentInfo{de.me.start/test.start.StartActivitiy}:android.view.InflateException:二进制 XML 文件第 10 行:膨胀类 test.start.control Blockquote 时出错

但我可以在图形布局中查看控件。

4

2 回答 2

4

尝试提供另一个版本的构造函数:

public control(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}
于 2011-03-21T11:36:32.647 回答
0

您应该通过以下方式在 XML 中声明它:

<view class="de.test.start.control"
              android:id="@+id/control" 
              android:layout_width="match_parent" 
              android:layout_height="match_parent"> </view>
于 2011-03-21T11:14:26.763 回答