2011-03-21 44 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

相關問題