开发者

simple custom class extends view

i want to create a custom view class. But I get an error by run the app.

here my class:

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);     
    }
}

and the 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>

Error Message:

Unable to start activity ComponentInfo{de.me.start/test.start.StartActivitiy}: android.view.InflateException: Binary XML file line #10: Error inflating class test.start.control Blockquote

But i can view the control in the graphical layout.


Try providing another version of the constructor:

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


You should declare it in the XML in the following way:

<view class="de.test.start.control"
              android:id="@+id/control" 
              android:layout_width="match_parent" 
              android:layout_height="match_parent"> </view>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜