[英]how to use a custom view in a xml file in android
這是我使用自定義視圖的xml。 該視圖位於另一個名為com.soft.MyView的程序包中,正在擴展視圖的類也稱為MyView,現在強制關閉並且logcat中的錯誤為07-21 16:26:29.936:ERROR / AndroidRuntime(19854):原因:android.view.InflateException:二進制XML文件第12行:膨脹類com.soft.MyView.MyView ..plss的錯誤告訴我我在哪里錯了?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/RelativeLayout1" xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/TextView1" android:layout_alignParentLeft="true" android:layout_alignParentTop="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<com.soft.MyView.MyView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/TextView1" android:layout_centerHorizontal="true" android:layout_marginTop="187dp" android:id="@+id/drawingImageView"/>
</RelativeLayout>
這是我的班級MyView
public class MyView extends View{
class Pt{
float x, y;
Pt(float _x, float _y){
x = _x;
y = _y;
}
}
Pt[] myPath = { new Pt(100, 100),
new Pt(200, 200),
new Pt(200, 500),
new Pt(400, 500),
new Pt(400, 200)
};
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStrokeWidth(3);
paint.setStyle(Paint.Style.STROKE);
Path path = new Path();
path.moveTo(myPath[0].x, myPath[0].y);
for (int i = 1; i < myPath.length; i++){
path.lineTo(myPath[i].x, myPath[i].y);
}
canvas.drawPath(path, paint);
}
}
語法<yourcompletepackagename.YourCustomClassName ..../>
<com.soft.MyView
^^^^^^
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/TextView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="187dp"
android:id="@+id/drawingImageView"/>
問題的原因是您僅使用了代碼版本的CTOR:
引自android開發人員指南:
從代碼創建視圖時使用的簡單構造函數。
解決方案是添加自定義視圖需要的所有可能的CTOR,以進行布局放大,或者至少添加以下一個:
引自android開發人員指南:
從XML擴展視圖時調用的構造方法。 當從XML文件構造視圖並提供XML文件中指定的屬性時,將調用此方法。 此版本使用默認樣式0,因此僅應用屬性值是上下文主題和給定AttributeSet中的屬性值。
您需要在MyView中重寫其他構造函數。 而不是只有這個構造函數:
public MyView(Context context) {
super(context);
}
創建自定義視圖時,至少也需要覆蓋此視圖:
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.