2011-03-21 42 views
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 /测试.start.StartActivitiy}: android.view.InflateException:Binary XML文件行#10:错误充气 类test.start.control 块引用

但我可以查看图形布局的控制。

回答

4

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

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

工作正常。非常感谢! – passsy 2011-03-21 13:13:35

0

你应该在以下方式中的XML声明它:

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

你试图再次运行前清理的项目? – MByD 2011-03-21 11:30:27

+0

我做到了。有没有任何示例项目,预定义的类扩展视图? – passsy 2011-03-21 11:56:44

+0

@Passy Hi Passy,你有没有找到你搜索的任何示例项目?...请与我们分享,如果有的话。谢谢 – 2012-03-03 05:05:40

相关问题